Ruby正则表达式匹配重叠术语

时间:2011-12-30 20:14:57

标签: ruby regex

我正在使用:

r = /(hell|hello)/

"hello".scan(r)  #=>   ["hell"]

但我想获得[ "hell", "hello" ]

http://rubular.com/r/IxdPKYSUAu

4 个答案:

答案 0 :(得分:6)

您可以使用发烧友捕获:

'hello'.match(/((hell)o)/).captures
=> ["hello", "hell"]

答案 1 :(得分:1)

不,正则表达式不是那样的。但你可以这样做:

terms = %w{hell hello}.map{|t| /#{t}/}

str = "hello"

matches = terms.map{|t| str.scan t}

puts matches.flatten.inspect # => ["hell", "hello"]

答案 2 :(得分:0)

好吧,你总能拿出共同的子表达式。即,以下工作:

r = /hello{0,1}/

"hello".scan(r)  #=>   ["hello"]
"hell".scan(r)   #=>   ["hell"]

答案 3 :(得分:-1)

你可以这样做:

r = /(hell|(?<=hell)o)/

"hello".scan(r)  #=>   ["hell","o"]

它不会给您["hell", "hello"],而是["hell", "o"]