$1 and \1 in Ruby

后端 未结 2 1392
再見小時候
再見小時候 2020-12-07 15:59

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

2条回答
  •  失恋的感觉
    2020-12-07 16:26

    Keep in mind there's a third option, the block form of sub. Sometimes you need it. Say you want to replace some text with the reverse of that text. You can't use $1 because 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 use \1, because the sub method just does a simple text-substitution of \1 with the appropriate captured text, there's no magic taking place here:

    "foobar".sub(/(.*)/, '\1'.reverse) # WRONG: returns '1\'
    

    So if you want to do anything fancy, you should use the block form of sub ($1, $2, $`, $' etc. will be available):

    "foobar".sub(/.*/){|m| m.reverse} # => returns 'raboof'
    "foobar".sub(/(...)(...)/){$1.reverse + $2.reverse} # => returns 'oofrab'
    

提交回复
热议问题