Regular Expressions (Regex) Explained with Examples
What is a regular expression?
A regular expression (regex) is a pattern that describes a set of strings. Programs use regexes to search text, check its format, extract parts of it and replace matches. The syntax combines literal characters with special symbols for character classes, repetition, position and grouping, and it works in nearly every language, including Python, PHP and JavaScript.
Key terms: pattern, match, metacharacter and flag
- Pattern: the regex itself, such as
\d{6}for six digits. - Match: a part of the input text that fits the pattern.
- Metacharacter: a character with special meaning, such as
. * + ? ^ $ ( ) [ ] { } | \. Put a backslash before it to match it literally, as in\.. - Capture group: a bracketed part of the pattern whose match you can read back separately.
- Flag (modifier): an option that changes how matching works, such as case-insensitivity.
Regex syntax: the building blocks
| Syntax | Meaning | Example matches |
|---|---|---|
abc | Literal characters | "abc" |
. | Any character except a newline | "a", "7", "#" |
[aeiou], [^0-9] | Character class; ^ inside negates it | a vowel; any non-digit |
\d \w \s | Digit, word character (letter, digit, underscore), whitespace | "5", "_", " " |
* + ? | Zero or more, one or more, zero or one | colou?r matches "color" and "colour" |
{3}, {2,4} | Exactly 3; between 2 and 4 | \d{4} matches "2026" |
*? +? | Lazy versions: match as little as possible | ".+?" stops at the first closing quote |
^ $ \b | Start, end, word boundary | \bcat\b matches "cat" but not "catalogue" |
( ), (?: ) | Capturing group; non-capturing group | (\d{2})-(\d{2}) |
a|b | Alternation: either side | ERROR|WARN |
Named groups make patterns readable: (?P<year>\d{4}) in Python and (?<year>\d{4}) in JavaScript. PHP accepts both forms. A backreference such as \1 matches the same text a group captured earlier, so \b(\w+) \1\b finds doubled words like "the the".
Lookarounds and flags
Lookarounds check what comes before or after a position without including it in the match. (?=...) is a positive lookahead, (?!...) a negative lookahead, (?<=...) a positive lookbehind and (?<!...) a negative lookbehind. For example, \d+(?= rupees) matches "250" in "250 rupees" but leaves out the word.
| Flag | Python | PHP / JavaScript | Effect |
|---|---|---|---|
| Ignore case | re.IGNORECASE | i | Upper and lower case match each other |
| Multiline | re.MULTILINE | m | ^ and $ match at each line |
| Dot matches newline | re.DOTALL | s | . also matches \n |
| Verbose | re.VERBOSE | x (PHP only) | Ignore whitespace and allow comments in the pattern |
| Global | Use findall or finditer | g (JavaScript only) | Find every match, not just the first |
Regex in Python, PHP and JavaScript
Python: the re module
import re
log = "2026-11-10 09:15:02 ERROR db timeout\n2026-11-10 09:16:40 WARN slow query"
line = re.compile(r"^(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>[\d:]{8}) (?P<level>ERROR|WARN|INFO)", re.MULTILINE)
for m in line.finditer(log):
print(m["date"], m["level"]) # 2026-11-10 ERROR, then 2026-11-10 WARN
print(re.findall(r"\b\d{6}\b", "Pune 411001, Delhi 110001")) # ['411001', '110001']
print(re.sub(r"\s+", " ", "too many spaces")) # too many spaces
print(bool(re.fullmatch(r"[A-Z]{4}0[A-Z0-9]{6}", "SBIN0001234"))) # True: IFSC formatre.search() finds the first match anywhere, re.match() only at the start and re.fullmatch() only if the whole string fits, which is what you want for format checks.
PHP: preg functions
<?php
$text = 'Order #A-1042 shipped on 2026-11-08, order #B-2210 pending';
if (preg_match('/#([A-Z])-(\d+)/', $text, $m) === 1) {
echo $m[0], ' ', $m[1], ' ', $m[2], PHP_EOL; // #A-1042 A 1042
}
preg_match_all('/#(?<series>[A-Z])-(?<num>\d+)/', $text, $all);
echo implode(', ', $all['num']), PHP_EOL; // 1042, 2210
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', $text), PHP_EOL;
// Order #A-1042 shipped on 08/11/2026, order #B-2210 pendingPHP patterns sit between delimiters, usually slashes, with flags after the closing one, as in /hello/i. Add the u flag when the text is UTF-8, such as Hindi or other non-ASCII input.
JavaScript: RegExp literals
const text = "Call 98765 43210 or 91234 56789";
for (const m of text.matchAll(/(\d{5}) (\d{5})/g)) {
console.log(m[1] + m[2]); // 9876543210, then 9123456789
}
console.log(/^[a-z0-9_]{3,16}$/i.test("Asha_2026")); // true
console.log("2026-11-10".replace(/(\d{4})-(\d{2})-(\d{2})/, "$3/$2/$1")); // 10/11/2026 Catastrophic backtracking and ReDoS
Most regex engines, including those in Python, PHP (PCRE) and JavaScript, backtrack: when part of a pattern fails, they go back and try other ways to split the input. Nested quantifiers such as ^(a+)+$ give an exponential number of ways, so a string of 30 "a" characters followed by "!" can make the engine work for a very long time. Attackers can trigger this deliberately with crafted input, a denial-of-service attack known as ReDoS, which OWASP documents.
- Avoid nested quantifiers and overlapping alternatives such as
(\w|\d)+. - Make patterns specific:
[^"]*instead of.*between quotes. - Limit input length before matching untrusted text.
- Use atomic groups
(?>...)or possessive quantifiersa++, available in PCRE and in Python since 3.11, to stop needless backtracking. - In PHP, check whether a
preg_function returnedfalse, then readpreg_last_error_msg(); hittingpcre.backtrack_limitis reported that way.
Do not validate email with an overly strict regex
Valid email addresses can contain plus signs, long new domain endings, subdomains and characters most hand-written patterns reject, so a strict regex turns away real users. A loose check catches typos; the only real proof is sending a confirmation link.
import re
def looks_like_email(value: str) -> bool:
return re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", value) is not None
print(looks_like_email("[email protected]")) # True
print(looks_like_email("asha@localhost")) # FalseIn PHP, filter_var($email, FILTER_VALIDATE_EMAIL) is the standard check, as used in form handling. Also avoid regex for parsing HTML or JSON; use a real parser, such as the one described in working with JSON.
Practical exercise: extract data from a log file
- Create a text file with ten log lines in the format
2026-11-10 09:15:02 LEVEL message, mixing INFO, WARN and ERROR. - Write a Python script that uses one compiled pattern with named groups to count lines per level.
- Print the time of every ERROR line, then use
re.sub()to rewrite each date as DD/MM/YYYY. - Write the same count in PHP with
preg_match_all()and confirm the totals match. - Test your pattern against a 10,000-character line of spaces and check that it returns quickly.
You are done when both scripts report the same counts and you can explain each part of your pattern. The PHP Foundation course uses regex for validating and processing form input.
Common mistakes
- Forgetting to escape metacharacters, so
.in a domain name matches any character. - Using
re.match()or a pattern without anchors for format checks, so extra text after a valid part slips through. - Writing greedy
.*where a lazy or negated class is needed, which swallows too much text. - Running nested-quantifier patterns on untrusted input, which risks catastrophic backtracking.
- Rejecting real email addresses with an over-strict pattern instead of sending a confirmation link.
Frequently asked questions
Are regexes the same in every language?
The core syntax is shared, but details differ. JavaScript has no possessive quantifiers, Python names groups with (?P<name>...), and flags are written differently in each language, so test patterns in the language you will use.
How do I test a regex quickly?
Use an interactive Python session or a short script with several matching and non-matching examples. Online regex testers also help, but select the right flavour and never paste private data into them.
When should I not use a regular expression?
Avoid regex for nested formats such as HTML, JSON or code; use a parser. For simple fixed text, string methods such as startswith() or str_contains() are clearer and faster.