Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$1 and \1 in Ruby

Tags:

regex

ruby

When using regular expressions in Ruby, what is the difference between $1 and \1?

like image 256
readonly Avatar asked Nov 13 '08 22:11

readonly


People also ask

What is $1 in Ruby?

The $1 is group matched from the regular expression above /(. +)_id$/ . The $1 variable is the string matched in the parenthesis.

What does =~ mean in Ruby?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.


1 Answers

\1 is a backreference which will only work in the same sub or gsub method call, e.g.:

"foobar".sub(/foo(.*)/, '\1\1') # => "barbar" 

$1 is a global variable which can be used in later code:

if "foobar" =~ /foo(.*)/ then    puts "The matching word was #{$1}" end 

Output:

"The matching word was bar" # => nil 
like image 57
Avdi Avatar answered Sep 17 '22 14:09

Avdi