What is a regular expression (regex)?
A Regex (Regular Expression) is a sequence of characters that forms a search pattern. Developers use it in JavaScript, PHP, Python or Java to search for, validate or replace specific elements in a text string.
The most famous use case is checking an email address: making sure it contains an "@" followed by a domain and an extension.
Regex cheat sheet: the essentials
- \d : A digit (0 to 9).
- \w : An alphanumeric character (letter, digit or underscore).
- \s : A whitespace character (space, tab).
- ^ : The start of the string.
- $ : The end of the string.
- [a-z] : Any lowercase letter.
- + : One or more occurrences.
- * : Zero or more occurrences.
What do the "flags" (modifiers) mean?
Modifiers (or flags) go at the end of the regex (after the last slash) to change its behavior:
- g (Global) : Without this flag, the regex stops at the first match found. With "g", it extracts all matches in the text.
- i (Insensitive) : Makes the search case-insensitive (uppercase and lowercase letters are treated the same).
- m (Multiline) : Means the symbols
^and$apply to the start and end of each line of the text, not of the whole text.