This content originally appeared on DEV Community and was authored by Shelner
Overview
A regular expression is a special pattern of characters used to find, match, or replace text in strings.
Think of it like a smart search took – instead of looking for exact words, it can look for patterns like:
- “all emails”
- “every number”
- “any word that ends with
.com“ - “dates like 2025-06-27”
Basic Parts of Regular Expressions
Here are some simple and common elements:
| Symbol | Meaning | Example | What it Matches |
|---|---|---|---|
. |
Any one character | a.b |
aab, acb, a1b
|
* |
0 or more of the previous thing | go* |
g, go, goo, goooooo
|
+ |
1 or more of the previous thing | go+ |
go, goo, but not g
|
? |
0 or 1 of the previous thing | colou?r |
color or colour
|
\d |
A digit (0-9) | \d\d\d |
123, 456
|
\w |
A word character (letter, number, or _) |
\w+ |
hello123, user_name
|
\s |
A whitespace (space, tab, etc.) | \s+ |
spaces, tabs, etc. |
^ |
Start of string | ^Hello |
matches strings that start with Hello
|
$ |
End of string | world$ |
matches strings that end with world
|
[abc] |
One of a, b, or c | gr[ae]y |
gray or grey
|
[^abc] |
Not a, b, or c | [^0-9] |
anything thats not a digit |
(abc) |
Grouping | (ha)+ |
ha, hahaha
|
Simple Examples
- Match an email:
/\w+@\w+\.\w+/-> matches things likejohn@example.com - Match a phone number:
/\d{3}-\d{3}-\d{4}/-> matches123-456-7890 - Match a date (YYYY-MM-DD):
/\d{4}-\d{2}-\d{2}/-> matches2025-06-27
This content originally appeared on DEV Community and was authored by Shelner