Basic Regex Syntax
Regular expressions (regex) are patterns used to match character combinations in strings. Here's the fundamental syntax:
| Pattern | Meaning | Example |
|---|---|---|
. | Any character (except newline) | h.t matches "hat", "hot" |
* | Zero or more of previous | ab*c matches "ac", "abc", "abbc" |
+ | One or more of previous | ab+c matches "abc", "abbc" (not "ac") |
? | Zero or one of previous | colou?r matches "color", "colour" |
^ | Start of string | ^Hello matches "Hello world" |
$ | End of string | world$ matches "Hello world" |
\ | Escape special character | \. matches a literal dot |
Character Classes
| Pattern | Meaning |
|---|---|
[abc] | Any of a, b, or c |
[^abc] | Not a, b, or c |
[a-z] | Any lowercase letter |
[A-Z] | Any uppercase letter |
[0-9] | Any digit |
\d | Digit (same as [0-9]) |
\w | Word character [a-zA-Z0-9_] |
\s | Whitespace (space, tab, newline) |
\D, \W, \S | Negated versions |
Quantifiers
{n} — Exactly n times \d{3} matches "123"
{n,} — n or more times \d{2,} matches "12", "123", "1234"
{n,m} — Between n and m \d{2,4} matches "12", "123", "1234"
*? — Lazy zero-or-more <.*?> matches first tag only
+? — Lazy one-or-more Shortest possible matchGroups and Alternation
(abc) — Capture group Match "abc" and remember it
(?:abc) — Non-capture group Match "abc" without remembering
(a|b) — Alternation Match "a" or "b"
\1 — Backreference Match same text as group 1Lookaheads and Lookbehinds
These assert that a pattern exists (or doesn't) without consuming characters:
(?=abc) — Positive lookahead "foo" followed by "bar": foo(?=bar)
(?!abc) — Negative lookahead "foo" NOT followed by "bar": foo(?!bar)
(?<=abc) — Positive lookbehind "bar" preceded by "foo": (?<=foo)bar
(?<!abc) — Negative lookbehind "bar" NOT preceded by "foo": (?<!foo)barCommon Real-World Patterns
// Email (simplified)
^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$ // URL
^https?:\/\/[\w.-]+\.[a-zA-Z]{2,}(\/\S*)?$ // IPv4 Address
^(\d{1,3}\.){3}\d{1,3}$ // Phone (US)
^\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$ // Hex Color
^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$ // Date (YYYY-MM-DD)
^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$ // Strong Password (8+ chars, upper, lower, digit, special)
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$Regex Flags
g— Global: find all matches, not just the firsti— Case-insensitive matchingm— Multiline: ^ and $ match line boundariess— Dotall:. matches newlines toou— Unicode: proper handling of Unicode characters
Test Your Regex
The best way to learn regex is to practice. Use our free Regex Tester to build, test, and debug patterns with real-time highlighting and match explanations. For more debugging tips, read our Regex Testing and Debugging guide.