olivM
olivM

Reputation: 33

Ruby regex matching overlapping terms

I'm using:

r = /(hell|hello)/

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

but I would like to get [ "hell", "hello" ].

http://rubular.com/r/IxdPKYSUAu

Upvotes: 3

Views: 823

Answers (4)

the Tin Man
the Tin Man

Reputation: 160571

You can use a fancier capture:

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

Upvotes: 6

nimrodm
nimrodm

Reputation: 23829

Well, you can always take out common subexpression. I.e., the following works:

r = /hello{0,1}/

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

Upvotes: 0

Jacob Eggers
Jacob Eggers

Reputation: 9332

You could do something like this:

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

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

It won't give you ["hell", "hello"], but rather ["hell", "o"]

Upvotes: -1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230461

No, regexes don't work like that. But you can do something like this:

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

str = "hello"

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

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

Upvotes: 1

Related Questions