January 14, 2025
O. Wolfson
Regex is a powerful tool for searching, matching, and manipulating strings. Understanding regular expressions (regex) requires knowing the basic building blocks used to match patterns in text.
Use the tool below to test your regex patterns:
apple"apple" in "I like apple pie."\).| Metacharacter | Meaning |
|---|---|
. | Matches any single character except newline |
^ | Matches the start of a string (a) |
$ | Matches the end of a string (b) |
* | Matches 0 or more of the preceding token |
+ | Matches 1 or more of the preceding token |
? | Matches 0 or 1 of the preceding token (optional) |
\ | Escapes a special character |
| | Logical OR (alternation) |
() | Groups expressions |
[] | Matches a set or range of characters |
^ Matches the start of a string, must be no characters before the
string to match. ^apple matches "apple" in "apple pie"$ Matches the end of a string, must be no characters after the string to match. apple$ matches "apple" in "I like apple pie"Examples:
(apple|banana|orange) matches "apple" in "apple pie" and "apple" in "pineapple"[abc] matches 'a', 'b', or 'c'.| Class | Meaning |
|---|---|
[abc] | Matches any character in the set |
[^abc] | Matches any character NOT in the set |
[a-z] | Matches any lowercase letter |
[0-9] | Matches any digit |
\d | Matches any digit ([0-9]) |
| Quantifier | Meaning |
|---|---|
* | Matches 0 or more times |
+ | Matches 1 or more times |
? | Matches 0 or 1 time (optional) |
{n} | Matches exactly n times |
{n,} | Matches n or more times |
a{2,4}"aa", "aaa", "aaaa"| Anchor | Meaning |
|---|---|
^ | Start of a string |
$ | End of a string |
\b | Word boundary |
\B | Non-word boundary |
Example:
^apple$"apple" (only if it's the entire string).\b(apple|banana|orange)\b matches "apple", "banana", or "orange" in "I like apple pie" but not "apple" in "pineapple"Used to group expressions or capture parts of a match.
Example:
(cat|dog)"cat" or "dog"Capturing:
(\d{3})-(\d{4})"123-4567" and captures "123" and "4567"Lookahead: Matches a group if it's followed by a specific pattern.
(?=pattern)(?!pattern)Lookbehind: Matches a group if it's preceded by a specific pattern.
(?<=pattern)(?<!pattern)Example:
\d(?= dollars)"5" in "5 dollars"i: Case-insensitiveg: Global (match all occurrences)m: Multiline (treat ^ and $ as start/end of a line)\ to escape metacharacters to match them literally.\$5"The price is $5"^\w+@\w+\.\w{2,}$^\(\d{3}\) \d{3}-\d{4}$https?://(www\.)?\w+\.\w+Regex is all about recognizing patterns using combinations of these elements. Start simple, build incrementally, and test as you go. There are many online tools like regex101 to practice and visualize matches.
\D |
| Matches any non-digit |
\w | Matches any word character ([a-zA-Z0-9_]) |
\W | Matches any non-word character |
\s | Matches any whitespace ([ \t\n\r\f\v]) |
\S | Matches any non-whitespace |
{n,m} |
Matches between n and m times |