3.11. Using Embedded OptionsThe 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 can use a colon followed by a subexpression, and those options specified will be in effect only for that subexpression: /ab(?i:cd)ef/ # Same as /ab(?i)cd(?-i)ef/ For technical reasons, it is not possible to treat the o option this way. The x option can be treated this way, but I don't know why anyone ever would. |