[ACCEPTED]-$1 and \1 in Ruby-regex
\1 is a backreference which will only work 3 in the same sub
or gsub
method call, e.g.:
"foobar".sub(/foo(.*)/, '\1\1') # => "barbar"
$1 is 2 a global variable which can be used in later 1 code:
if "foobar" =~ /foo(.*)/ then
puts "The matching word was #{$1}"
end
Output:
"The matching word was bar"
# => nil
Keep in mind there's a third option, the 10 block form of sub
. Sometimes you need it. Say 9 you want to replace some text with the reverse 8 of that text. You can't use $1 because 7 it's not bound quickly enough:
"foobar".sub(/(.*)/, $1.reverse) # WRONG: either uses a PREVIOUS value of $1,
# or gives an error if $1 is unbound
You also can't 6 use \1
, because the sub
method just does a simple 5 text-substitution of \1
with the appropriate 4 captured text, there's no magic taking place 3 here:
"foobar".sub(/(.*)/, '\1'.reverse) # WRONG: returns '1\'
So if you want to do anything fancy, you 2 should use the block form of sub
($1, $2, $`, $' etc. will 1 be available):
"foobar".sub(/.*/){|m| m.reverse} # => returns 'raboof'
"foobar".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab'
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.