7

I have a list of strings, and need to build the regular expression from them, using Regexp#union. I need the resulting pattern to be case insensitive.

The #union method itself does not accept options/modifiers, hence I currently see two options:

strings = %w|one two three|

Regexp.new(Regexp.union(strings).to_s, true)

and/or:

Regexp.union(*strings.map { |s| /#{s}/i })

Both variants look a bit weird.

Is there an ability to construct a case-insensitive regular expression by using Regexp.union?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Note that your first option `Regexp.new(Regexp.union(strings).to_s, true)` returns `/(?-mix:one|two|three)/i` which is probably not what you want, because the words are still matched case sensitive (`-i`). – Stefan Sep 08 '17 at 07:15

2 Answers2

12

The simple starting place is:

words = %w[one two three]
/#{ Regexp.union(words).source }/i # => /one|two|three/i

You probably want to make sure you're only matching words so tweak it to:

/\b#{ Regexp.union(words).source }\b/i # => /\bone|two|three\b/i

For cleanliness and clarity I prefer using a non-capturing group:

/\b(?:#{ Regexp.union(words).source })\b/i # => /\b(?:one|two|three)\b/i

Using source is important. When you create a Regexp object, it has an idea of the flags (i, m, x) that apply to that object and those get interpolated into the string:

"#{ /foo/i }" # => "(?i-mx:foo)"
"#{ /foo/ix }" # => "(?ix-m:foo)"
"#{ /foo/ixm }" # => "(?mix:foo)"

or

(/foo/i).to_s  # => "(?i-mx:foo)"
(/foo/ix).to_s  # => "(?ix-m:foo)"
(/foo/ixm).to_s  # => "(?mix:foo)"

That's fine when the generated pattern stands alone, but when it's being interpolated into a string to define other parts of the pattern the flags affect each sub-expression:

/\b(?:#{ Regexp.union(words) })\b/i # => /\b(?:(?-mix:one|two|three))\b/i

Dig into the Regexp documentation and you'll see that ?-mix turns off "ignore-case" inside (?-mix:one|two|three), even though the overall pattern is flagged with i, resulting in a pattern that doesn't do what you want, and is really hard to debug:

'foo ONE bar'[/\b(?:#{ Regexp.union(words) })\b/i] # => nil

Instead, source removes the inner expression's flags making the pattern do what you'd expect:

/\b(?:#{ Regexp.union(words).source })\b/i # => /\b(?:one|two|three)\b/i

and

'foo ONE bar'[/\b(?:#{ Regexp.union(words).source })\b/i] # => "ONE"

You can build your patterns using Regexp.new and passing in the flags:

regexp = Regexp.new('(?:one|two|three)', Regexp::EXTENDED | Regexp::IGNORECASE) # => /(?:one|two|three)/ix

but as the expression becomes more complex it becomes unwieldy. Building a pattern using string interpolation remains more easy to understand.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • That's interesting. It didn't occur to me that `"Twosome" =~ /\b#{ Regexp.union(words).source }\b/i #=> 0`. Hence the need to put `#{ Regexp.union(words).source }` in a group. Nor did I know about `source`. – Cary Swoveland Jul 02 '16 at 03:59
  • `source`, of course, thanks! Great explanation, btw. – Aleksei Matiushkin Jul 02 '16 at 05:09
  • 3
    I use a lot of patterns for parsing text, and `source` was core to being able to combine simple patterns into more complex ones. – the Tin Man Jul 03 '16 at 17:41
  • http://stackoverflow.com/questions/43057658/how-to-embed-regular-expressions-in-other-regular-expressions-in-ruby has more information. – the Tin Man Mar 28 '17 at 01:34
0

You've overlooked the obvious.

strings = %w|one two three|

r = Regexp.union(strings.flat_map do |word| 
  len = word.size
  (2**len).times.map { |n|
    len.times.map { |i| n[i]==1 ? word[i].upcase : word[i] } }
end.map(&:join))

 "'The Three Little Pigs' should be read by every building contractor" =~ r
   #=> 5      
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • 1
    That would work, yes; even more: with properly patched `String#upcase` is will even work with _utf8_ strings, like with cyrillic (while standard Ruby regexps still lack this functionality.) – Aleksei Matiushkin Jul 01 '16 at 18:49
  • This an absurd answer. I'd downvote it if I could. Suppose `r` is the regex computed for `strings = ["one", "two", "three hundred seventy"]`. Sure, it works (`"There were tHRee HuNDred sevENTy cats" =~ r #=> 11`), but `r.to_s.count('|') #=> 2097167`! – Cary Swoveland Jul 01 '16 at 20:50
  • 1
    I know, I know ;) I am not going to use it in prod, only at home. – Aleksei Matiushkin Jul 01 '16 at 20:53
  • TIL that one can use index access to get bits from an integer :tada: – rewritten Mar 31 '21 at 10:57