How to Use Regular Expressions (Regex): A Beginner's Guide
Regex (regular expressions) are patterns for matching text. They look cryptic at first β ^[\w.-]+@[\w.-]+\.\w{2,}$ β but every character follows a small set of simple rules. Once you learn those rules, you can write patterns for almost any text-matching problem.
The Core Syntax
Literal characters
The simplest regex is just the text you're looking for. The pattern cat matches the string "cat" anywhere in the input.
Character classes
| Pattern | Matches | Example |
|---|---|---|
| . | Any single character (except newline) | h.t matches "hat", "hit", "hot" |
| \d | Any digit 0β9 | \d\d matches "42", "07" |
| \w | Word character (letter, digit, underscore) | \w+ matches "hello", "user_123" |
| \s | Whitespace (space, tab, newline) | \s+ matches spaces between words |
| [aeiou] | Any character inside the brackets | [aeiou] matches any vowel |
| [^aeiou] | Any character NOT inside the brackets | [^aeiou] matches consonants |
| [a-z] | Any character in the range | [a-z0-9] matches lowercase + digits |
Quantifiers
| Quantifier | Meaning |
|---|---|
| * | 0 or more times |
| + | 1 or more times |
| ? | 0 or 1 time (optional) |
| {3} | Exactly 3 times |
| {2,5} | Between 2 and 5 times |
| {3,} | 3 or more times |
Anchors
^ Start of string β ^Hello matches "Hello world" but not "Say Hello"
$ End of string β world$ matches "Hello world" but not "world peace"
\b Word boundary β \bcat\b matches "cat" but not "catch" or "concatenate"
Real-World Examples
Email validation
^[\w.-]+@[\w.-]+\.\w{2,}$ One or more word chars/dots/hyphens before @, then a domain, then a TLD of at least 2 characters.
β Does not match
user@@example.comnotanemail Phone number (flexible)
^[+]?[(]?\d{1,4}[)]?[-\s.]?\d{1,4}[-\s.]?\d{4,9}$ Optional country code, optional brackets, digits separated by spaces, dashes, or dots.
β Matches
+62 812 3456 78900812-3456-7890(021) 5551234 β Does not match
abc-def-ghij123 Extract URLs
https?:\/\/[\w.-]+(?:\/[\w.\-/?=#&%]*)? http or https, then ://, then domain and optional path.
β Matches
https://webkitters.comhttp://example.com/path?q=1 β Does not match
ftp://example.comjust text Test Your Regex
Use our Regex Tester to build and test patterns against your own text. It highlights matches in real time and shows capture groups β the fastest way to iterate on a pattern.
Test regex patterns in real time