Skip to content
Pwnversity
FUND-REGEXbasic · 15 min · upd. 2026-11

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.

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

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.

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.

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.

  • Capturing (...): besides grouping, it stores what matched so you can use it later (\1 inside the pattern, $1 or \1 in the replacement, or group(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)\1 finds double letters (ll in hello).

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.

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)

On an authentication log and on tool output from a lab machine:

Ventana de terminal
# Unique IPs with failed passwords, sorted by number of attempts
grep '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 dump
grep -oE '[[:alnum:]._%+-]+@[[:alnum:].-]+\.[[:alpha:]]{2,}' dump.txt
grep -oE 'https?://[^[:space:]"<>]+' dump.txt
grep -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 report
sed -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 repo
rg -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 untouched
ip = 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 groups
m = 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 references
print(re.sub(r'(\w+)@(\w+)\.local', r'\2/\1', 'ana@lab.local')) # lab/ana
# Compile it if you'll use it many times
md5_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.

These come up again and again when reviewing code or testing filters:

  1. No anchors. re.search(r'[a-z0-9]+', user) accepts admin;id, because admin fits somewhere. You have to validate the whole string (fullmatch, or ^...$ with match).
  2. $ lets a trailing newline through. In Python, ^[a-z0-9]+$ accepts "admin\n", because $ also matches right before a final \n. fullmatch or \Z reject it.
  3. The unescaped dot. ^https://lab.local accepts https://labXlocal.evil, because . is any character. And lab\.local without anchors accepts https://lab.local.evil.com. To validate domains or origins, parse the URL and compare the exact host instead.
  4. 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.
  5. 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, time
t = time.time(); re.match(r'(a+)+$', 'a' * 24 + '!'); print(round(time.time() - t, 2)) # ~0.6 s
t = time.time(); re.match(r'a+$', 'a' * 24 + '!'); print(round(time.time() - t, 4)) # ~0.0001 s

Every 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).

  • 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.
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
  1. 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.

  2. grep 'a+' file doesn’t find aaa. Why?

    Answer

    Because plain grep uses BRE, where an unescaped + is a literal character: it looks for the text a+ as is. To mean “one or more” you need grep -E 'a+' or, in GNU grep, grep 'a\+'.

  3. 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;id or x' OR '1'='1. Without anchors, search finds the part that fits and accepts the whole string. It should use re.fullmatch(r'[a-z0-9]+', user).

  4. What’s the difference between (GET|POST) (\S+) and (?:GET|POST) (\S+) when used with re.findall?

    Answer

    With the first, findall returns tuples with two groups (method and path). With the second, the method is grouped without capturing and findall returns only the path.

  5. You want only the value after user= from a log, without the user= itself. What two ways do you have with grep -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.

  6. Why doesn’t ^https://lab.local work for checking that a link points to lab.local?

    Answer

    Because the unescaped dot accepts any character (https://labXlocal...) and because, with no end anchor or check on what follows, it accepts https://lab.local.evil.com. The right way is to parse the URL and compare the exact host.

  7. 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.