Ruby 中的 $1 和 \1 [英] $1 and \1 in Ruby
本文介绍了Ruby 中的 $1 和 \1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Ruby 中使用正则表达式时,$1 和 \1 有什么区别?
When using regular expressions in Ruby, what is the difference between $1 and \1?
推荐答案
\1 是一个反向引用,它只适用于同一个 sub
或 gsub
方法调用,例如:
\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 是一个全局变量,可以在后面的代码中使用:
$1 is a global variable which can be used in later code:
if "foobar" =~ /foo(.*)/ then
puts "The matching word was #{$1}"
end
输出:
"The matching word was bar"
# => nil
这篇关于Ruby 中的 $1 和 \1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文