Reputation: 33
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
Reputation: 160571
You can use a fancier capture:
'hello'.match(/((hell)o)/).captures
=> ["hello", "hell"]
Upvotes: 6
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
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
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