What are Regular Expressions?
Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They are supported in virtually every programming language and are incredibly powerful for text validation, searching, and transformation.
Basic Regex Syntax
| Pattern | Meaning | Example |
|---|---|---|
. | Any single character | c.t matches "cat", "cut", "c3t" |
* | 0 or more of previous | ab* matches "a", "ab", "abb" |
+ | 1 or more of previous | ab+ matches "ab", "abb" (not "a") |
? | 0 or 1 of previous | colou?r matches "color" and "colour" |
^ | Start of string | ^Hello matches strings starting with "Hello" |
$ | End of string | world$ matches strings ending with "world" |
[] | Character class | [aeiou] matches any vowel |
[^] | Negated character class | [^0-9] matches any non-digit |
{n,m} | n to m repetitions | d{3,5} matches 3 to 5 digits |
d | Any digit (0-9) | d+ matches one or more digits |
w | Word character [a-zA-Z0-9_] | w+ matches a word |
s | Whitespace | s+ matches spaces, tabs, newlines |
Common Regex Patterns
- Email:
[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,} - URL:
https?://(www.)?[-a-zA-Z0-9@:%._+~#=]{2,256}.[a-z]{2,6} - Phone (US):
+?1?s?(?d{3})?[s.-]?d{3}[s.-]?d{4} - ZIP Code:
d{5}(-d{4})? - Date (YYYY-MM-DD):
d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]d|3[01]) - IP Address:
(?:d{1,3}.){3}d{1,3}
Regex Flags
g— Global: find all matches, not just the firsti— Case insensitive: treat uppercase and lowercase as equalm— Multiline:^and$match start/end of each line
Tips for Writing Regex
- Start simple and build up complexity gradually
- Always test with edge cases (empty strings, very long strings)
- Use named groups (
(?<name>...)) for complex patterns - Avoid greedy matching when possible — use
*?and+? - Comment complex regex using the
xflag (where supported)
Practice your regex patterns with our free Regex Tester — it highlights all matches in real time as you type.