Basic Regex Syntax

Regular expressions (regex) are patterns used to match character combinations in strings. Here's the fundamental syntax:

PatternMeaningExample
.Any character (except newline)h.t matches "hat", "hot"
*Zero or more of previousab*c matches "ac", "abc", "abbc"
+One or more of previousab+c matches "abc", "abbc" (not "ac")
?Zero or one of previouscolou?r matches "color", "colour"
^Start of string^Hello matches "Hello world"
$End of stringworld$ matches "Hello world"
\Escape special character\. matches a literal dot

Character Classes

PatternMeaning
[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
\dDigit (same as [0-9])
\wWord character [a-zA-Z0-9_]
\sWhitespace (space, tab, newline)
\D, \W, \SNegated 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 match

Groups 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 1

Lookaheads 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)bar

Common 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 first
  • i — Case-insensitive matching
  • m — Multiline: ^ and $ match line boundaries
  • s — Dotall:. matches newlines too
  • u — 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.