如何使用Regexp.union构建不区分大小写的正则表达式

我有一个字符串列表,需要使用Regexp#union从它们构建正则表达式。 我需要得到的模式不区分大小写

#union方法本身不接受选项/修饰符,因此我目前看到两个选项:

 strings = %w|one two three| Regexp.new(Regexp.union(strings).to_s, true) 

和/或:

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

两种变体看起来都有些奇怪。

是否有能力使用Regexp.union构造不区分大小写的正则表达式?

简单的起点是:

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

可能想确保你只匹配单词,所以调整它:

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

为了清洁和清晰,我更喜欢使用非捕获组:

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

使用source很重要。 当你创建一个Regexp对象时,它知道应用于该对象的标志( imx )以及那些被插入到字符串中的标志:

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

要么

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

当生成的模式独立时,这很好,但是当它被插入到字符串中以定义模式的其他部分时,标志会影响每个子表达式:

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

深入了解Regexp文档,你会看到?-mix关闭里面的“ignore-case” (?-mix:one|two|three) ,即使整个模式用i标记,导致一个模式没有做你想做的事,而且很难调试:

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

相反, source删除内部表达式的标志,使模式执行您期望的操作:

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

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

可以使用Regexp.new构建模式并传入标志:

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

但随着表达变得更加复杂,它变得笨拙。 使用字符串插值构建模式仍然更容易理解。

你忽视了显而易见的事实。

 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