regex-banderas

Flags in Regex

  • 3 min

Flags are options we can apply to a regular expression to change its matching behavior.

These options can be specified at the beginning of the regular expression, after a forward slash, or within parentheses, depending on the programming language used.

Some of the most common flags are:

SymbolFunction
gGlobal mode, searches for all matches
iIgnore case
mMultiline mode
sAllows the dot (.) to match newline characters
xAllows including whitespace and comments
uEnables the use of Unicode characters

Not all of them are available in all languages

Modifier g (Global Match)

Performs matches across the entire text (not just the first occurrence).

El año es 2024 y el día es 24.

It is the default behavior in many languages

Modifier i (Case Insensitive)

Ignores uppercase/lowercase in the search.

Hola, hola, y HOLA a todo el mundo!

Here, the Regex selects all variants of “hola”, regardless of case.

Modifier m (Multi-line)

Allows ^ and $ to match the start and end of lines (not just the entire string)

La primera línea

Una línea que no empieza por La

La tercera línea

Here, ^La selects the word “La” that appears at the beginning of each line, not just at the start of the text.

Modifier s (Dot All)

Allows the dot (.) to match newline characters (\n), in addition to any other character.

Hola

aqui cosas en medio

mundo!

Here, the regex selects the text between “Hola” and “mundo”, even crossing lines thanks to the s modifier.

Modifier u (Unicode)

Enables full Unicode character matching.

ñ, é, and ß are valid Unicode letters.

Here, \p{L} selects any Unicode letter, such as ñ, é and ß.

Modifier x (Verbose)

Allows comments and spaces within the regex for better readability. Comments are added with #.

We found 1234 and 5678 in the document.

Here, all numbers with more than one digit are selected, while the comment after # does not affect the regex.

Don’t overuse this, as it often complicates things more than it improves them