Regular Expressions
A regular expression (regex) is a pattern that describes a set of text strings. You use it to search, extract, validate or replace text. It’s in grep and sed, in every editor, in Python, in WAF rules and in SIEM detection rules. In practice it does two jobs for you: it turns the output of a tool, or a log with thousands of lines, into the ten lines you care about, and it lets you understand why an application’s validation lets through what it shouldn’t.
Concepts
Section titled “Concepts”Literals and metacharacters
Section titled “Literals and metacharacters”Most characters stand for themselves: admin finds admin. A few have a special meaning, and to search for them literally you escape them with \.
| Symbol | Means | Example | Matches |
|---|---|---|---|
. |
Any character (except newline) | a.c |
abc, a-c, a.c |
^ · $ |
Start · end of the string (or line) | ^root |
root only at the start |
* |
The previous element, 0 or more times | ab*c |
ac, abc, abbbc |
+ |
1 or more times | ab+c |
abc, abbc, not ac |
? |
0 or 1 time (optional) | https? |
http, https |
{n,m} |
Between n and m times | \d{2,4} |
12, 123, 1234 |
[...] |
One of the listed characters | [aeiou] |
a vowel |
| |
Alternation: one thing or the other | GET|POST |
GET or POST |
(...) |
Groups and captures | (ab)+ |
ab, abab |
\ |
Removes (or adds) special meaning | \. |
an actual dot |
Classes and shorthands
Section titled “Classes and shorthands”A class [...] is a single character from a set. Ranges work inside it ([a-z], [0-9a-f]), and a leading ^ negates it: [^"] is any character that isn’t a double quote.
| Shorthand | Same as | Negation |
|---|---|---|
\d |
A digit, [0-9] |
\D |
\w |
Letter, digit or _, [A-Za-z0-9_] |
\W |
\s |
Whitespace (space, tab, newline) | \S |
[[:digit:]] · [[:alpha:]] · [[:alnum:]] · [[:space:]] |
POSIX classes, the ones grep understands without -P |
— |
In Python 3, \d and \w include Unicode digits and letters (ñ, ٣); use re.ASCII or [0-9] if you want ASCII only.
Anchors and boundaries
Section titled “Anchors and boundaries”Without anchors, the pattern matches anywhere in the text: admin matches superadmin123. ^admin$ requires the string to be exactly admin. \b marks a word boundary (between a \w character and one that isn’t): \badmin\b finds admin in user=admin; but not in superadmin.
Greedy versus lazy
Section titled “Greedy versus lazy”The quantifiers *, + and {n,m} are greedy: they swallow as much as they can and then back off just enough for the rest to fit. Followed by ? (*?, +?) they become lazy: they take as little as possible.
An example with this HTML:
<a href="/uno">1</a><a href="/dos">2</a>| Pattern | Captures | Why |
|---|---|---|
href="(.*)" |
/uno">1</a><a href="/dos |
.* runs to the last quote on the line |
href="(.*?)" |
/uno and /dos |
.*? stops at the first quote |
href="([^"]*)" |
/uno and /dos |
More explicit and faster: “anything that isn’t a quote” |
The third form is usually best: it says exactly what you want and doesn’t depend on how the engine behaves.
Groups
Section titled “Groups”- Capturing
(...): besides grouping, it stores what matched so you can use it later (\1inside the pattern,$1or\1in the replacement, orgroup(1)in Python). - Non-capturing
(?:...): groups without storing. Handy for applying a quantifier or an alternation without cluttering the results:(?:GET|POST) (\S+)returns only the path. - Named
(?P<user>\w+)in Python ((?<user>...)in PCRE): you get the group back by name and the pattern reads better. - Backreference
\1: forces a repeat of exactly what group 1 captured.(\w)\1finds double letters (llinhello).
Lookahead and lookbehind
Section titled “Lookahead and lookbehind”They check what comes after or before without consuming it (it isn’t part of the match). They don’t exist in BRE/ERE (grep, grep -E, sed) or in RE2/Go/Rust (rg without -P); they do in PCRE (grep -P), Python, modern JavaScript, Java, .NET…
| Form | Name | Example |
|---|---|---|
X(?=Y) |
Positive lookahead | \w+(?= from): the word right before from |
X(?!Y) |
Negative lookahead | admin(?!istrator): admin not followed by istrator |
(?<=Y)X |
Positive lookbehind | (?<=user=)\w+: the value of user= |
(?<!Y)X |
Negative lookbehind | (?<!\\)": unescaped quotes |
grep -P also has \K, which drops everything before it from the match: Failed password for \K\S+ prints only the username.
Flavours: not all regexes are the same
Section titled “Flavours: not all regexes are the same”There are several engine families and each tool uses one. What works in Python may not work in grep without options.
| Tool | Family | + ? | {} () |
\d \w |
Lookarounds |
|---|---|---|---|---|
grep |
BRE (basic) | Must be escaped: \+ \{2\} \( |
\d no (use [0-9]); \w \s yes in GNU |
No |
grep -E · egrep |
ERE (extended) | Yes, unescaped | \d no (use [0-9] or [[:digit:]]); \w \s yes in GNU |
No |
grep -P |
PCRE (Perl-like) | Yes | Yes | Yes, plus \K |
sed · sed -E |
BRE · ERE | Same as grep · grep -E |
\d no (use [0-9]); \w \s yes in GNU |
No |
Python re |
Its own, very close to PCRE | Yes | Yes | Yes |
| JavaScript | Its own | Yes | Yes | Yes (lookbehind since ES2018) |
In practice
Section titled “In practice”On an authentication log and on tool output from a lab machine:
# Unique IPs with failed passwords, sorted by number of attemptsgrep 'Failed password' auth.log | grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' | sort | uniq -c | sort -rn# 2 10.10.10.5# 1 192.168.56.20
# Usernames that were tried (PCRE: \K drops what came before)grep -oP 'Failed password for (invalid user )?\K\S+' auth.log# root# admin
# Emails, URLs and hashes in any text dumpgrep -oE '[[:alnum:]._%+-]+@[[:alnum:].-]+\.[[:alpha:]]{2,}' dump.txtgrep -oE 'https?://[^[:space:]"<>]+' dump.txtgrep -oE '\b[0-9a-f]{32}\b' dump.txt # length of an MD5 (or NTLM)grep -oE '\b[0-9a-f]{64}\b' dump.txt # length of a SHA-256
# Transform with sed -E: anonymise IPs before pasting a log into the reportsed -E 's/([0-9]{1,3}\.){3}[0-9]{1,3}/[IP]/g' auth.log
# rg (ripgrep): recursive, fast and honours .gitignore; handy on a downloaded reporg -i 'pass(word|wd)?\s*[:=]' loot/In Python, the re module:
import re
line = "Failed password for invalid user admin from 192.168.56.20 port 40122 ssh2"
# Always write patterns as raw strings (r'...') so \d reaches re untouchedip = re.search(r'from (\S+) port', line)print(ip.group(1)) # 192.168.56.20
# findall returns every match (or the groups, if there are any)html = '<a href="/uno">1</a><a href="/dos">2</a>'print(re.findall(r'href="([^"]*)"', html)) # ['/uno', '/dos']
# Named groupsm = re.search(r'(?P<user>\w+)@(?P<dom>[\w.]+)', 'write to ana@lab.local')print(m.group('user'), m.group('dom')) # ana lab.local
# Replace using group referencesprint(re.sub(r'(\w+)@(\w+)\.local', r'\2/\1', 'ana@lab.local')) # lab/ana
# Compile it if you'll use it many timesmd5_hash = re.compile(r'\b[0-9a-f]{32}\b', re.IGNORECASE)match only looks at the start of the string, search anywhere, and fullmatch requires the whole string to match. Mixing them up is behind many broken validations.
Why regex validation fails
Section titled “Why regex validation fails”These come up again and again when reviewing code or testing filters:
- No anchors.
re.search(r'[a-z0-9]+', user)acceptsadmin;id, becauseadminfits somewhere. You have to validate the whole string (fullmatch, or^...$withmatch). $lets a trailing newline through. In Python,^[a-z0-9]+$accepts"admin\n", because$also matches right before a final\n.fullmatchor\Zreject it.- The unescaped dot.
^https://lab.localacceptshttps://labXlocal.evil, because.is any character. Andlab\.localwithout anchors acceptshttps://lab.local.evil.com. To validate domains or origins, parse the URL and compare the exact host instead. - Multiline mode. With
re.MULTILINE,^and$match at the start and end of every line:re.search(r'^\d+$', "x\n123", re.M)accepts the string. An attacker only needs one line that passes. - Blocklists. A filter looking for
<script>doesn’t catch<ScRiPt>,<svg onload=...>or encodings. That’s why you validate with allowlists and encode output, instead of trying to list everything that’s forbidden.
ReDoS: when the regex takes the server down
Section titled “ReDoS: when the regex takes the server down”Some patterns with nested quantifiers make the engine try an exponential number of combinations when the input almost matches. This is catastrophic backtracking, and if the regex processes user input it’s a denial of service (ReDoS).
import re, timet = time.time(); re.match(r'(a+)+$', 'a' * 24 + '!'); print(round(time.time() - t, 2)) # ~0.6 st = time.time(); re.match(r'a+$', 'a' * 24 + '!'); print(round(time.time() - t, 4)) # ~0.0001 sEvery extra a doubles the time of the first pattern: a few more and it’s minutes. The dangerous shapes are quantifiers inside quantifiers ((a+)+, (\w*)*) and overlapping alternations ((a|aa)+). You avoid them by simplifying the pattern, capping input length before applying it, or using backtracking-free engines (RE2, Go’s regexp or Rust’s).
Next offensive step
Section titled “Next offensive step”- Bypassing filters and WAFs that rely on regex: WAF evasion.
- Regex as the building block of detection rules: YARA and SIEM.
- Automating extraction and validation in your scripts: Python for hacking.
Cheat sheet
Section titled “Cheat sheet”| Concept | What to remember |
|---|---|
. |
Any character. For a literal dot, \. |
* · + · ? |
0 or more · 1 or more · 0 or 1 |
{n,m} |
Between n and m repetitions |
[abc] · [^abc] · [a-z] |
One from the list · one not in it · a range |
\d \w \s |
Digit · word character · whitespace. Uppercase negates |
^ · $ · \b |
Start · end · word boundary |
.* versus .*? |
Greedy (as much as possible) versus lazy (as little) |
(...) · (?:...) · \1 |
Capture · group without capturing · repeat the capture |
(?=...) · (?<=...) |
Look ahead · look behind, without consuming |
grep · grep -E · grep -P |
BRE (escape \+) · ERE · PCRE (lookarounds, \K) |
r'...' |
Raw string in Python, always for patterns |
search · match · fullmatch |
Anywhere · at the start · the whole string |
| Validating | Anchored, allowlist, fullmatch. Never just a blocklist |
(a+)+ |
Nested quantifier: ReDoS risk |
Review questions
Section titled “Review questions”-
What does
href="(.*)"return on a line with two links, and how do you fix it?Answer
Everything from the first quote of the first link to the last quote on the line, because
.*is greedy. Fix it with.*?(lazy) or, better,[^"]*, which can’t skip past a quote. -
grep 'a+' filedoesn’t findaaa. Why?Answer
Because plain
grepuses BRE, where an unescaped+is a literal character: it looks for the texta+as is. To mean “one or more” you needgrep -E 'a+'or, in GNU grep,grep 'a\+'. -
An application validates the username with
re.search(r'[a-z0-9]+', user). What dangerous input does it let through?Answer
Anything that contains a letter or digit somewhere, such as
admin;idorx' OR '1'='1. Without anchors,searchfinds the part that fits and accepts the whole string. It should usere.fullmatch(r'[a-z0-9]+', user). -
What’s the difference between
(GET|POST) (\S+)and(?:GET|POST) (\S+)when used withre.findall?Answer
With the first,
findallreturns tuples with two groups (method and path). With the second, the method is grouped without capturing andfindallreturns only the path. -
You want only the value after
user=from a log, without theuser=itself. What two ways do you have withgrep -P?Answer
A lookbehind,
grep -oP '(?<=user=)\w+', or\K,grep -oP 'user=\K\w+'. Both check the prefix without including it in the output. -
Why doesn’t
^https://lab.localwork for checking that a link points tolab.local?Answer
Because the unescaped dot accepts any character (
https://labXlocal...) and because, with no end anchor or check on what follows, it acceptshttps://lab.local.evil.com. The right way is to parse the URL and compare the exact host. -
What is ReDoS and what kind of pattern causes it?
Answer
A denial of service where crafted input makes the regex engine take exponential time because of backtracking. It’s caused by nested quantifiers (
(a+)+,(\w*)*) and overlapping alternations, when the input almost matches but fails at the end.
References
Section titled “References”- Python —
remodule and Regular Expression HOWTO - GNU grep — regular expressions
- GNU sed — regular expressions
- regex101: test and explain patterns per engine
- OWASP — Regular expression Denial of Service (ReDoS)