Regex Matching Modes (Page 17)
Most regular expression engines discussed in this tutorial support the following four matching modes:
Modifier | Description |
|---|---|
/i | Makes the regex case-insensitive. |
/s | Enables "single-line mode," making the dot ( |
/m | Enables "multi-line mode," allowing caret ( |
/x | Enables "free-spacing mode," where whitespace is ignored, and |
Specifying Modes Inside The Regular Expression
You can specify these modes within a regex using mode modifiers. For example:
(?i)turns on case-insensitive matching.(?s)enables single-line mode.(?m)enables multi-line mode.(?x)enables free-spacing mode.
Example:
(?i)hello matches "HELLO"Turning Modes On and Off for Only Part of the Regex
Modern regex flavors allow you to apply modifiers to specific parts of the regex:
(?i-sm)turns on case-insensitive mode while turning off single-line and multi-line modes.
To apply a modifier to only a part of the regex, you can use the following syntax:
(?i)word(?-i)WordThis pattern makes "word" case-insensitive but "Word" case-sensitive.
Modifier Spans
Modifier spans apply modes to a specific section of the regex:
(?i:word)makes "word" case-insensitive.(?i:case)(?-i:sensitive)applies mixed modes within the regex.
Example:
(?i:ignorecase)(?-i:casesensitive)Understanding matching modes is essential for writing efficient and accurate regex patterns. By leveraging modes like case-insensitivity, single-line, multi-line, and free-spacing, you can create more flexible and maintainable regular expressions.
Recommended Comments