Regexp.union - set option all patterns case insensitive

J

John Honovich

I want to pull a list of terms and use them to scan documents to
determine if any of those words are present.

Let's say fruits = ["apples","oranges","grapes"].

I do Regexp.union(*fruits). This returns /apples|oranges|grapes/ which
is good.

Now I want this pattern to be case insensitive, i.e. -
/apples|oranges|grapes/i

Docs say I can set each argument to case insensitive and then call union
e.g. - Regexp.union(/dogs/, /cats/i) #=>
/(?-mix:dogs)|(?i-mx:cats)/


I have been doing fruits.map!{|fruit| Regexp.new(fruit,
Regexp::IGNORECASE)}; Regexp.union(*fruits)

This seems to work. Is there any better or cleaner way to do this?

Thanks,

John
 
C

Chris Shea

I want to pull a list of terms and use them to scan documents to
determine if any of those words are present.

Let's say fruits = ["apples","oranges","grapes"].

I do Regexp.union(*fruits). This returns /apples|oranges|grapes/ which
is good.

Now I want this pattern to be case insensitive, i.e. -
/apples|oranges|grapes/i

Docs say I can set each argument to case insensitive and then call union
e.g. - Regexp.union(/dogs/, /cats/i) #=>
/(?-mix:dogs)|(?i-mx:cats)/

I have been doing fruits.map!{|fruit| Regexp.new(fruit,
Regexp::IGNORECASE)}; Regexp.union(*fruits)

This seems to work. Is there any better or cleaner way to do this?

Thanks,

John

I don't know how much better this is, but you could union first, then
add the case-insensitivity:

fruits = ["apples","oranges","grapes"]
r = Regexp.union(*fruits)
r = Regexp.new(r.source, Regexp::IGNORECASE) # => /apples|oranges|
grapes/i

HTH,
Chris
 
B

Boson

Chris said:
I don't know how much better this is, but you could union first, then
add the case-insensitivity:

fruits = ["apples","oranges","grapes"]
r = Regexp.union(*fruits)
r = Regexp.new(r.source, Regexp::IGNORECASE) # => /apples|oranges|
grapes/i

This solution works. Thanks.

Looking at the Ruby source, it wouldn't be hard to add an options
parameter to Regexp.union to avoid such re-conversions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top