Scoped Pattern Modifiers
You may lexically
scope the /i, /m, /s,
/x, /d, /u,
/a, /l, and /p
modifiers within a portion of your pattern by inserting them (without
the slash) between the ? and : of the grouping notation. If you say:
/Harry (?i:s) Truman/
it matches both “Harry S
Truman” and “Harry s
Truman”, whereas:
/Harry (?x: [A–Z] \.? \s )?Truman/
matches both “Harry S Truman”
and “Harry S. Truman”, as well as
“Harry Truman”; and:
/Harry (?ix: [A–Z] \.? \s )?Truman/
matches all five, by combining the /i and /x
within the group.
You can also subtract modifiers from a scope with a minus sign:
/Harry (?x–i: [A–Z] \.? \s )?Truman/i
This matches any capitalization of the name—but if the middle
initial is provided, it must be capitalized, since the /i applied to the overall pattern is suspended
inside the scope.
When subtracting, you may only subtract /i, /m,
/s, or /x. The /d, /u, /a,
/l, and /p modifiers may only be added.
By omitting both colon and PATTERN, you
can export modifier settings to an outer group, turning it into a scope.
That is, you can selectively turn modifiers on and off for the grouping
construct one level outside the modifiers’ parentheses, like so:
/(?i)foo/ # Equivalent to /foo/i /foo((?–i)bar)/i # "bar" must be lower case /foo((?x–i)bar)/ # Enables /x and disables /i for "bar"
Note that the second and third examples create capture groups. If
that wasn’t what you wanted, then you should have been using (?–i:bar) and (?x–i:bar), respectively.
Setting modifiers on a portion of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access