
Powerful tools for matching patterns within text
Literals: The simplest type of regex. Match the exact characters you specify.
Metacharacters
Define a character class. Match any single character inside the brackets.
| Mark | Description |
|---|---|
. | Match any single character except a newline. |
^ | Anchor the match at the start of a string. |
$ | Anchor the match at the end of a string. |
[] | Define a character class. Match any single character inside the brackets. |
| | | Alternation operator. Match either the pattern before or the pattern after the ' | '. |
() | Group patterns together. |
Quantifiers: Specify how many instances of a character, group, or character class must be present in the input for a match to be found.
| Mark | Description |
|---|---|
* | Match 0 or more instances. |
+ | Match 1 or more instances. |
? | Match 0 or 1 instance. |
{n} | Match exactly n instances. |
{n,} | Match n or more instances. |
{n,m} | Match between n and m instances. |
Character Classes
| Mark | Description |
|---|---|
[abc] | Match any one of a, b, or c. |
[a-z] | Match any lowercase letter from a to z. |
[^abc] | Match any character except a, b, or c. |
Escape Sequences
| Mark | Description |
|---|---|
\. | Match a literal period. |
\\ | Match a literal backlash. |
\d | Match any digit (equivalent to [0-9]). |
\D | Match any non-digit. |
\w | Match any word character (equivalent to [a-zA-Z0-9_]). |
\W | Match any non-word character. |
\s | Match any whitespace character (spaces, tabs, etc.). |
\S | Match any non-whitespce character. |
a.*b matches the longest possible string starting with a and ending with b.? after a quantifier makes it lazy. a.*?b matches the shortest possible string starting with a and ending with b.| Assertions | Mark | Description |
|---|---|---|
| Positive Lookahead | (?=…) | Example: a(?=b) matches a if it is followed by b, but b is not part of the match. |
| Negative Lookahead | (?!…) | Example: a(?!b) matches a if it is not followed by b. |
| Positive Lookbehind | (?<=…) | Example: (?<=b)a matches a if it is preceded by b. |
| Negative Lookbehind | (?<!…) | Example: (?<!b)a matches a if it is not preceded by b. |