How to create a case-insensitive regular expression with Regexp.union

I have a list of strings and you need to build a regex from them using Regexp#union . I need the resulting pattern case insensitive.

The #union method #union does not accept parameters / modifiers, so currently I 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 options look a little strange.

Is it possible to build a case-insensitive regular expression using Regexp.union ?

+4
source share
2 answers

Simple starting place:

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

You probably want to make sure that you only match the words, so tweak this:

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

For clarity and clarity, I prefer to use the group without capturing:

 /\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 this object, and they are inserted into the line:

 "#{ /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)" 

This is good when the generated template stands alone, but when it is interpolated into a string to define other parts of the template, the flags affect each subexpression:

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

Take a look at the Regexp documentation and you will see that ?-mix disables the "ignore case" inside (?-mix:one|two|three) , even if the generic pattern is marked i , which leads to the pattern that doesn't do what you want and really hard to debug:

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

Instead, source removes the flags of the internal expression, causing the template to do what you 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 create your own templates using Regexp.new and passing flags:

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

but when the expression becomes more complex, it becomes cumbersome. Building a template using string interpolation remains easier to understand.

+7
source

You ignored 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 
0
source

Source: https://habr.com/ru/post/1265990/


All Articles