regex-modificadores-inline

What are inline modifiers in regular expressions and how to use them

  • 3 min

Inline modifiers are very similar to flags, but they can be included directly within a regular expression.

That is, 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 have compatibility with 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:

ModifierDescription
(?i)Ignores differences between uppercase and lowercase
(?m)Multiline 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.

Hola, hola, y HOLA a todo el mundo!

In this example, we use (?i) to allow “hola” to match regardless of its capitalization.

Modifier m (Multi-line)

The m modifier allows the anchors ^ and $ to work on each line of a text.

La primera línea

Una línea que no empieza por La

La tercera línea

Here, (?m) allows ^ to match the beginning of “Segunda” in the second line of the text.

Modifier s (Dot All)

The s modifier allows the dot (.) to match newline characters.

Hola

aqui cosas en medio

mundo!

Here, (?s) makes .* match the line break between “Hola,” and “¿cómo estás?”.

Modifier x (Verbose)

The x modifier allows including spaces and comments in the expression, improving its readability.

We found 1234 and 5678 in the document.

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 need to join the modifiers in our (?mod).

For example, if we want a match that

  • Is case-insensitive (?i)
  • Works on multiple lines (?m)

We can do it simply 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 putting modifiers)