When using regular expressions in Ruby, what is the difference between $1 and \1?
The $1 is group matched from the regular expression above /(. +)_id$/ . The $1 variable is the string matched in the parenthesis.
=~ 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 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With