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:
| Symbol | Function | ||
|---|---|---|---|
g | Global mode, searches for all matches | ||
i | Ignore case | ||
m | Multiline mode | ||
s | Allows the dot (.) to match newline characters | ||
x | Allows including whitespace and comments | ||
u | Enables 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).
It is the default behavior in many languages
Modifier i (Case Insensitive)
Ignores uppercase/lowercase in the search.
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)
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.
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.
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 #.
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
