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

Ale*_*kin 5 ruby regex

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

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

strings = %w|one two three|

Regexp.new(Regexp.union(strings).to_s, true)
Run Code Online (Sandbox Code Playgroud)

和/或:

Regexp.union(*strings.map { |s| /#{s}/i })
Run Code Online (Sandbox Code Playgroud)

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

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

the*_*Man 10

简单的起点是:

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

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

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

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

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

使用source很重要.当你创建一个RegExp对象,它具有标志(的想法i,m,x适用于该对象,并得到那些插值到字符串):

"#{ /foo/i }" # => "(?i-mx:foo)"
"#{ /foo/ix }" # => "(?ix-m:foo)"
"#{ /foo/ixm }" # => "(?mix:foo)"
Run Code Online (Sandbox Code Playgroud)

要么

(/foo/i).to_s  # => "(?i-mx:foo)"
(/foo/ix).to_s  # => "(?ix-m:foo)"
(/foo/ixm).to_s  # => "(?mix:foo)"
Run Code Online (Sandbox Code Playgroud)

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

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

深入研究Regexp文档,您会看到?-mix内部关闭"忽略大小写" (?-mix:one|two|three),即使整个模式被标记i,导致模式无法满足您的需求,并且很难调试:

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

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

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

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

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

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

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

  • 我使用了很多模式来解析文本,而`source`是能够将简单模式组合成更复杂模式的核心. (3认同)