具有反向引用的正则表达式

时间:2012-10-30 04:18:46

标签: ruby regex

有人可以解释后面引用在ruby正则表达式中的确切作用吗?我特别想知道(..)分组的确切工作原理。例如:

s = /(..) [cs]\1/.match("The cat sat in the hat")

puts s 

对于上面的代码段,输出为:at sat。为什么/如何获得此输出?

2 个答案:

答案 0 :(得分:18)

这是正则表达式的含义:

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"

另请注意,the Regexp#match method返回一个MatchData对象,该对象包含导致整个匹配的字符串(“at sat”,又名$&),然后是每个匹配组(“at”,aka { {1}}):

$1

答案 1 :(得分:2)

首先,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"]