Regex basics cheatsheet
A regular expression (regex) is a pattern that matches text. Each symbol, called a token, changes how the pattern behaves. The cheatsheet below lists the tokens you will reach for most, with a plain-English meaning and a small example you can copy and test.
| Token | Meaning | Example |
|---|---|---|
| . | Matches any single character except newline. | a.c matches abc, a c |
| * | Matches the preceding token zero or more times. | ab* matches a, abb |
| + | Matches the preceding token one or more times. | ab+ matches ab, abb |
| ? | Makes the preceding token optional (zero or one). | colou?r matches color, colour |
| [] | Character set: matches any one character inside. | [aeiou] matches any vowel |
| [^] | Negated set: matches any character NOT inside. | [^0-9] matches any non-digit |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches any whitespace (space, tab, newline). | a\sb matches a b |
| ^ | Anchors the match to the start of a line/string. | ^Hello matches start of string |
| $ | Anchors the match to the end of a line/string. | world$ matches end of string |
| | | Alternation: matches the pattern on either side. | cat|dog matches cat or dog |
| () | Groups a sub-pattern (and captures it). | (ab)+ matches ab, abab |
| {n,m} | Quantifier: match the preceding token n to m times. | a{2,4} matches aa, aaaa |
| (?i) | Inline flag: makes the pattern case-insensitive. | (?i)hello matches HELLO |
Notes
- Most tokens lose their special meaning inside a character set [ ]. For example, . inside [] just matches a literal dot.
- Backslash (\), the escape character, turns a special token into a literal character and vice versa.
- Engines differ: Python, JavaScript, PCRE and Golang share most tokens but flags and look-around support vary.
Frequently asked questions
- What does the dot (.) match?
- By default the dot matches any single character except a newline. To match a literal dot you must escape it as \.
- What is the difference between * and +?
- The asterisk * matches the preceding token zero or more times, so 'ab*' matches 'a' too. The plus + requires at least one, matching 'ab' but not just 'a'.
- How do I match a digit or a word character?
- Use \d for any digit (0-9) and \w for any word character (letters, digits and underscore). Their negations are \D and \W.
- What do ^ and $ do?
- ^ anchors the match to the start of the string or line; $ anchors it to the end. Together, ^pattern$ forces the whole string to match.