3.11. Using Embedded Options

The common way to specify options for a regex is to use a trailing option (such as i or m). But what if we want an option to apply only to part of a regular expression?

We can turn options on and off with a special notation. Within parentheses, a question mark followed by one or more options “turns on” those options for the remainder of the regular expression. A minus sign preceding one or more options “turns off” those options:

/abc(?i)def/         # Will match abcdef, abcDEF, abcDef, ...
                     #   but not ABCdef
/ab(?i)cd(?-i)ef/    # Will match abcdef, abCDef, abcDef, ...
                     #   but not ABcdef or abcdEF
/(?imx).*/           # Same as /.*/imx
/abc(?i-m).*/m       # For last part of regex, turn on case
                     #   sensitivity, turn off multiline

If we want, we ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.