CakeFest 2024: The Official CakePHP Conference

内部选项设置

PCRE_CASELESSPCRE_MULTILINEPCRE_DOTALLPCRE_UNGREEDYPCRE_EXTRAPCRE_EXTENDED、 PCRE_DUPNAMES 等模式修饰符设置可以在模式内部通过一个 Perl 选项字符序列来设置, 语法是 (?修饰符),可用的修饰符有:

Internal option letters
i for PCRE_CASELESS
m for PCRE_MULTILINE
s for PCRE_DOTALL
x for PCRE_EXTENDED
U for PCRE_UNGREEDY
X for PCRE_EXTRA
J for PCRE_INFO_JCHANGED

比如,(?im) 设置表明多行大小写不敏感匹配。同样可以用它来取消这些设置, 比如 (?im-sx) 设置了 PCRE_CASELESSPCRE_MULTILINE, 但是同时取消了 PCRE_DOTALLPCRE_EXTENDED。 如果一个字母即出现在 - 之前, 也出现在 - 之后,这个选项被取消设置。

当一个选项在模式的最上级(也就是说不在子组中)时, 这个改变会影响模式中剩余部分。比如 /ab(?i)c/ 仅仅匹配 ”abc” 和 ”abC”。

如果一个选项在子组中设置,产生的影响是不同的。这是 Perl 5.005 中行为的一个变种。 一个选项在子组内部设置,仅仅改变子组中剩余的部分, 因此 (a(?i)b)c 仅仅匹配 ”abc” 和 ”aBc” (假设没有使用 PCRE_CASELESS 选项)。 这就意味着选项在模式的不同位置可以造成不同的影响。 在同一个子模式中, 一个分支的选项设置回穿透到后面剩余的其他分支中去。 比如 (a(?i)b|c) 匹配”ab”, “aB”, “c” 和 ”C”。 尽管在匹配 ”C” 时第一个分支会在选项被设定前就被丢弃。 这是因为选项的设定是在编译期确定的,否则可能会带来非常怪异的行为。

PCRE 专用选项 PCRE_UNGREEDYPCRE_EXTRA 可以和 Perl 兼容选项以同样的方式来改变, 分别使用字母 U 和 X。 (?X) 标记设定有些特殊,它必须出现在任何其他特性之前, 最好放在最开头的位置。

add a note

User Contributed Notes 2 notes

up
3
mike at clove dot com
14 years ago
When using the (?i:foo) syntax, it appears that the group is not included in the 'matches' argument unless it is nested in an additional set of parenthesis, for example: ((?i:foo))
up
2
mati_ at zenbe dot com
14 years ago
There is also the possibility to enable Modifier only on a specific group, so that the Modifier doesn't stay valid until end or deactivation with "(?-<modifier>)".

The Syntax for that is "?<modifier>:" on the beginning of the group, i.e. (?i:foo) matches on FoO.
To Top