我正在浏览 about_regular_expressions.rb 并且不明白这里发生了什么:
def test_variables_can_also_be_used_to_access_captures
assert_equal "Gray, James", "Name: Gray, James"[/(\w+), (\w+)/]
assert_equal "Gray", $1
assert_equal "James", $2
end
在我看来,正则表达式中括号的使用在幕后创建了两个新变量($1 和 $2)。
它是否正确?
但后来我这样做了:
def test_variables_can_also_be_used_to_access_captures
assert_equal "Gray, James", "Name: Gray, James"[/(\w+), (\w+)/]
assert_equal "Smith, Bobert", "Name: Smith, Bobert"[/(\w+), (\w+)/]
assert_equal "Smith", $1
assert_equal "Bobert", $2
end
它捕获了“史密斯”和“博伯特”。我猜每次使用带括号的新正则表达式时,以前的值都会被覆盖?
如果我尝试只捕捉一个词:
def test_variables_can_also_be_used_to_access_captures
assert_equal "Gray, James", "Name: Gray, James"[/(\w+), (\w+)/]
assert_equal "Smith, Bobert", "Name: Smith, Bobert"[/(\w+), (\w+)/]
assert_equal "Smith", $1
assert_equal "Bobert", $2
assert_equal "Susan,", "Name: Susan, whatever"[/(\w+),/]
assert_equal "Susan", $1
assert_equal nil, $2
end
2 美元不见了……(不再是“鲍勃”)
任何人都可以阐明引擎盖下发生的事情吗?或者指出我正确的方向?