Regular expressions in a nutshell
1. What is a regex?
A regular expression (regex) is a compact pattern that describes text. Developers use regexes to validate input such as emails and phone numbers, search logs, extract data and run find-and-replace across files.
2. Cheat sheet
| Syntax | Meaning |
|---|---|
^ / $ | Start / end of string or line |
. | Any character except a line break |
\d \w \s | Digit, word character, whitespace |
[abc] / [^abc] | One of / none of the listed characters |
* + ? | 0+, 1+, 0 or 1 times |
{2,5} | Between 2 and 5 times |
( ) / (?: ) | Capturing / non-capturing group |
a|b | a or b |
(?=…) (?!…) | Lookahead / negative lookahead |
Example: a Vietnamese mobile number can be matched with ^(0|\+84)(3|5|7|8|9)\d8$.
Frequently asked questions
Which regex flavour does this use?
JavaScript (ECMAScript) regular expressions, the same engine used by browsers and Node.js. Most syntax is shared with Python, Java, PHP and .NET, but advanced features can differ.
How do I match a literal dot or question mark?
Escape it with a backslash: \. matches a dot and \? matches a question mark. Without the backslash, . means "any character" and ? means "optional".
What is the difference between greedy and lazy quantifiers?
Quantifiers such as * and + are greedy by default and match as much text as possible. Add ? after them (for example .*?) to make them lazy, matching as little as possible.
Is my test text sent anywhere?
No. Matching and explanation run entirely in your browser.