任何人都可以解释反向引用在 ruby 正则表达式中是如何工作的吗?我特别想知道(..)分组是如何工作的。例如:
s = /(..) [cs]\1/.match("The cat sat in the hat")
puts s 
对于上面的代码片段,输出是:at sat. 为什么/如何得到这个输出?
这是这个正则表达式的含义:
regex = /(..) [cs]\1/
#        ├──┘ ├──┘├┘
#        │    │   └─ A reference to whatever was in the first matching group.
#        │    └─ A "character class" matching either "c" or "s".
#        └─ A "matching group" referenced by "\1" containing any two characters.
请注意,在将正则表达式与匹配组匹配后,特殊变量$1($2等) 将包含匹配的内容。
/(..) [cs]\1/.match('The cat sat in the hat') # => #<MatchData...>
$1 # => "at"
另请注意,该Regexp#match方法返回一个 MatchData 对象,其中包含导致整个匹配的字符串(“at sat”,aka $&),然后是每个匹配组(“at”,aka $1):
/(..) [cs]\1/.match('The cat sat in the hat')
=> #<MatchData "at sat" 1:"at"> 
首先,输出puts s不是捕获组:
s = /(..) [cs]\1/.match("The cat sat in the hat")
puts s
# at sat
如果你想访问它的捕获组,你应该使用MatchData.captures:
s = /(..) [cs]\1/.match("The cat sat in the hat")
s.captures
# => ["at"]