检查 'Regexp.union'

Inspection of 'Regexp.union'

Regexp.unionreturns检查如下:

Regexp.union(/dogs/, /cats/i) #=> /(?-mix:dogs)|(?i-mx:cats)/

?-mix: 是什么意思?

它们是正则表达式中的标志开关。 /cats/i 表示 "use flag i across the whole regexp"。您可以在正则表达式中打开和关闭标志,因此以上等同于 /(?i:cats)/。还有两个其他标志可以通过这种方式进行操作:mx。由于默认情况下所有标志都被禁用,除非另有说明,因此它等效于 /(?i-mx:cats)/ ("enable i and disable m and x inside the regular expression cats").

当您组合正则表达式时,它们会明确禁用禁用的标志,这样它们就不会从外部上下文继承它们。例如:

tiny = /tiny/             # case sensitive
tina = /#{tiny} tina/i    # case insensitive
# => /(?-mix:tiny) tina/i

这将匹配 "tiny tina""tiny Tina",但不会匹配 "Tiny Tina"。如果 tiny 的嵌入式正则表达式没有明确关闭区分大小写,而只是产生 /tiny tina/i,所有内容都会不区分大小写。

您看到的是子正则表达式选项的表示。连字符左边的选项是on,连字符右边的选项是off。明智的做法是将每个选项明确设置为打开或关闭,以确保在该正则表达式成为更大的正则表达式的一部分时正确的行为。

在您的示例中,(?-mix:dogs) 表示 mix 选项全部关闭,而在 (?i-mx:cats) 中,i 选项打开,因此该子表达式不区分大小写。

请参阅 Regexp Options 上的 Ruby 文档:

The end delimiter for a regexp can be followed by one or more single-letter options which control how the pattern can match.

  • /pat/i - Ignore case
  • /pat/m - Treat a newline as a character matched by .
  • /pat/x - Ignore whitespace and comments in the pattern
  • /pat/o - Perform #{} interpolation only once

i, m, and x can also be applied on the subexpression level with the (?on-off) construct, which enables options on, and disables options off for the expression enclosed by the parentheses.