Inline modifiers are very similar to flags, but we can include them directly within a regular expression.
That is to say, unlike global modifiers that apply to the entire expression, inline modifiers allow us to modify the behavior of the expression only in the part where they are inserted.
Not all languages and tools will support inline modifiers
Syntax of inline modifiers
Inline modifiers are specified using the syntax (?mod)
, where mod
is the modifier we want to apply.
The most common inline modifiers include:
Modifier | Description |
---|---|
(?i) | Ignores case differences |
(?m) | Multi-line modifier |
(?s) | Allows the dot (. ) to match newline characters. |
(?x) | Verbose mode |
Modifier i (Case Insensitive)
The i
modifier is useful when we want the match to be case insensitive.
In this example, we use (?i)
to allow “hello” to match regardless of its capitalization.
Modifier m (Multi-line)
The m
modifier allows the anchors ^
and $
to work on each line of text.
A line that does not start with The
The third line
Here, (?m)
allows ^
to match the start of “Second” in the second line of the text.
Modifier s (Dot All)
The s
modifier allows the dot (.
) to match newline characters.
here are some things in between
world!
Here, (?s)
makes .*
match the newline between “Hello,” and “how are you?“.
Modifier x (Verbose)
The x
modifier allows including spaces and comments in the expression, improving its readability.
With (?x)
, we can include comments in the expression to make it more understandable.
Combining inline modifiers
We can combine several inline modifiers in a single expression. To do this, we simply have to join the modifiers in our (?mod)
.
For example, if we want a match that
- Is case insensitive
(?i)
- Works across multiple lines
(?m)
We can do this by combining both modifiers like this (?im)
Tips
Inline modifiers are very powerful, but excessive use can lead to expressions that are difficult to read and maintain.
(a.k.a. don’t go overboard with modifiers)