Regular Expressions for Beginners
Learn the core regular expression symbols, build patterns step by step, and avoid common traps.
Key takeaways
- Most characters match themselves; a small set of metacharacters has special meaning and must be escaped to be literal.
- Character classes say which characters are allowed, and quantifiers say how many times.
- Use
^and$when the whole string must match, not just a part of it. - Regex dialects differ between tools, so test in the one you'll actually use.
- For structured formats such as HTML or JSON, use a real parser.
A regular expression, or regex, is a short pattern that describes a set of text strings. You use it to find, check, extract or replace text that follows a shape, such as every date in a log file or every line that starts with "ERROR". With about a dozen symbols you can handle most everyday jobs.
The syntax looks dense at first because each character carries meaning. The trick is to read a pattern one piece at a time and to build your own the same way.
Literal text and special characters
The pattern cat matches the letters c, a, t in that order, anywhere in the text. It finds "cat", and also the middle of "concatenate". Matching is usually case-sensitive unless you turn on an option.
These characters have special jobs: . ^ $ * + ? ( ) [ ] { } | \. To match one literally, put a backslash before it. So example\.com matches that domain, while example.com would also match "exampleXcom", because an unescaped dot means "any single character" (typically except a line break).
Forgetting to escape dots is probably the most common beginner mistake, and it matters when the pattern is used to decide whether something is trusted.
Character classes
Square brackets define a class: a set of characters, any one of which may appear at that position.
-
[aeiou]matches one vowel. -
[a-z]matches one lowercase ASCII letter. -
[A-Za-z0-9]matches one letter or digit. -
[^0-9]matches one character that is not a digit.
Inside a class, ^ at the start means "not", and a hyphen between two characters means a range. Most other metacharacters lose their special meaning there.
Shorthand classes save typing: \d for a digit, \w for a "word" character (letters, digits and underscore), \s for whitespace. The capital forms \D, \W and \S mean the opposite. Whether \w includes accented or non-Latin letters depends on the tool and its Unicode settings. If your data is international, read about character encoding and test with real samples.
Quantifiers: how many
A quantifier applies to the item immediately before it.
| Quantifier | Meaning | Example | Matches |
|---|---|---|---|
* | zero or more | ab* | a, ab, abbb |
+ | one or more | ab+ | ab, abbb |
? | zero or one | colou?r | color, colour |
{3} | exactly three | \d{3} | 123 |
{2,4} | two to four | \d{2,4} | 12, 123, 1234 |
{2,} | two or more | \d{2,} | 12, 1234567 |
Anchors and boundaries
Anchors match a position instead of a character. ^ means the start of the string (or of a line in multiline mode), and $ means the end. \b marks a word boundary, the edge between a word character and a non-word character.
Compare these three patterns against the text "concatenate":
-
catmatches, because it appears inside. -
\bcat\bdoesn't match, because "cat" isn't a separate word there. -
^cat$matches only a string that is exactly "cat".
For validating input, anchors are essential. Without them, a check for five digits would happily accept "abc12345xyz".
Building a pattern step by step
Say you want to find dates written like 2026-03-15 in a log. Start with the shape: four digits, a hyphen, two digits, a hyphen, two digits.
The pattern \b\d{4}-\d{2}-\d{2}\b finds things that look like dates. It also accepts month 99. You could tighten the month to (0[1-9]|1[0-2]) and the day to (0[1-9]|[12]\d|3[01]), but regex still won't know that February 31 doesn't exist. A good division of labor: let the pattern check the shape, and let date-handling code check whether the date is real.
Groups and alternation
Parentheses group parts of a pattern so a quantifier or choice can apply to all of them. The vertical bar means "or". (cat|dog)s? matches cat, cats, dog or dogs.
Parentheses also capture the matched text for later use. With (\d{4})-(\d{2})-(\d{2}), group 1 holds the year, group 2 the month and group 3 the day. Many tools let you refer to them in a replacement, written as $1 or \1 depending on the tool, so you can reorder a date without retyping it.
If you only need grouping, (?:...) creates a non-capturing group in most modern dialects. Many also support named groups such as (?<year>\d{4}), which make code easier to read.
Greedy and lazy matching
Quantifiers are greedy by default: they take as much as they can while still letting the overall pattern succeed. Given the text "one" and "two", the pattern ".*" matches from the first quote to the last, swallowing everything in between.
Two fixes work. Add ? after the quantifier to make it lazy: ".*?" stops at the first closing quote. Or, often better, say exactly what is allowed: "[^"]*" means a quote, any number of non-quotes, then a quote. The second version states your intent and tends to do less work.
Where you'll use them
# Linux and macOS: find lines containing a 4xx or 5xx status after a quote
grep -E '" [45][0-9]{2} ' access.log # Windows PowerShell
Select-String -Path .\app.log -Pattern '^ERROR\b' // JavaScript
const m = "Order 1042".match(/Order (\d+)/);
m[1] // "1042"
"a,b ;c".split(/\s*[,;]\s*/) Code editors offer regex find and replace, as do database query languages, web server rules and analytics filters. The find and replace tool is a convenient scratchpad for text you can paste.
Dialects matter. Traditional basic grep treats + and {} differently from grep -E, and it may not understand \d. Use [0-9] when you want portability. Features such as lookbehind aren't available everywhere.
Lookarounds and flags
Sometimes you want to require that something comes before or after a match without including it. Lookaheads do that. The pattern \d+(?= GB) matches the number in "16 GB" but leaves the unit out. A negative lookahead, (?!...), requires that something does not follow. Lookbehinds, written (?<=...) and (?<!...), check the text before the match, though not every engine supports them or allows variable lengths inside them.
Flags change how a whole pattern behaves. The common ones are:
- i: ignore letter case.
- g: in JavaScript and some editors, find every match instead of stopping at the first.
- m: multiline mode, where
^and$match at each line. - s: in many engines, lets the dot match line breaks as well.
- x: in some engines, allows spaces and comments inside the pattern for readability.
A worked example: pulling fields from a log
Suppose a hypothetical log line reads 2026-03-15 14:30:07 WARN user=ada ip=192.0.2.44 ms=812. You want the user and the duration from every warning.
Start with the level: \bWARN\b. The user is a run of non-space characters after user=, so add user=(\S+). Between the two there may be other text, which .*? covers. The duration is digits after ms=, written ms=(\d+). Joined together:
\bWARN\b.*?user=(\S+).*?\bms=(\d+) Group 1 holds the user and group 2 the duration. To find only slow requests of a second or more, change the second group to (\d{4,}). That works because any number with four or more digits is at least 1000, assuming the log never pads with leading zeros. Stating that assumption in a comment helps whoever maintains the pattern next.
When not to use regex
Nested formats such as HTML, XML and JSON have rules that simple patterns can't follow reliably. Use a parser. The same goes for CSV files with quoted commas and line breaks.
Email addresses are another trap. A fully faithful pattern is enormous and still can't tell you whether the mailbox exists. A loose check for something before and after an @, followed by a confirmation message, serves most sites better.
For a fixed string, ordinary string functions such as "contains" or "starts with" are clearer and faster.
Performance and safety
Some patterns force the engine to try an enormous number of combinations before giving up. The classic shape is a repeated group whose contents also repeat, such as (a+)+$, run against a long string that almost matches. This is called catastrophic backtracking, and on a server it can tie up a processor, a weakness known as regular expression denial of service.
To protect yourself, avoid nested or overlapping repetition, limit input length before matching, prefer specific classes over .*, and don't run patterns supplied by untrusted users without time limits or an engine designed to avoid backtracking.
Also remember that a regex check on input is only one defense. It doesn't replace parameterized database queries or output escaping, covered in injection and scripting flaws explained for builders.
Common questions
How do I ignore capital letters?
Set the case-insensitive option: the i flag in JavaScript, -i with grep. Select-String ignores case by default.
Why does my pattern work in a tester but not in code?
Check the dialect, the flags and the quoting. In many languages a backslash inside an ordinary string must be doubled, unless you use a raw string or a regex literal.