Skip to content
Reviewed by Siddharth Sharma Nov 24, 2026

Home › Guides › Regex cheat sheet

Tech Explained · 2026

Regex Cheat Sheet 2026: 40 Patterns, Worked Examples and the Backtracking Trap Behind Most Slow Matches

A regex cheat sheet is a compact reference to the metacharacters, quantifiers and groups a regular expression engine understands, plus the flavour differences between tools. This one covers 40 patterns across Python, PostgreSQL, BigQuery and Excel, each with a worked example, and shows which quantifier shapes make a match collapse from microseconds to seconds.

24 November 202612 min readBy the 360 Digital Transformation Editorial Team
Key takeaways
  • Quantifiers are the whole game. Nearly every regex that is wrong or slow is wrong because a quantifier was greedy when it should have been lazy, or nested inside another quantifier.
  • Flavours differ in ways that bite. Excel's new REGEX functions use PCRE2, BigQuery uses RE2 and refuses lookbehind entirely, and PostgreSQL only got regexp_like in version 15.
  • One shape causes most slow matches. A quantifier inside a quantifier, like (a+)+, makes match time double with every extra character. We measured 2.5 ms at 16 characters and 10.5 seconds at 28.
  • Python 3.11 gave you the fix. Possessive quantifiers and atomic groups landed in the standard library, and they turned that same 10.5 second match into 0.002 ms on our run.
  • Regex is the wrong tool for nested data. HTML, JSON and balanced brackets need a parser. Use regex on flat, line shaped text.
  • Write the test before the pattern. Five known-good and five known-bad inputs catch more bugs than rereading the pattern does.

Your validation script runs in a second against a sample of 500 policyholder rows. You point it at the full export of 1.2 million rows and come back to a process still running, one core pinned at 100%, no output and nothing in the log. That is almost always a regex, and the two-person data team at a mid-size Indian insurer we will follow through this guide hit exactly that on a Tuesday afternoon.

How a Regex Engine Actually Reads Your Pattern

Most engines in the tools you use daily, including Python's re, Java, .NET, JavaScript and PCRE2, are backtracking engines. They do not evaluate your pattern as a formula. They walk it character by character, and when a greedy quantifier has eaten too much they hand characters back one at a time, retrying the rest of the pattern at each step.

That retry loop is why regex feels magical on small inputs and lethal on large ones. For a simple pattern the loop is bounded by the input length. When a quantifier sits inside another quantifier, it is bounded by two raised to the input length.

The backtracking loop, in order

Every "no" in the bottom right sends the engine round again, which is where the time goes.

How a backtracking regex engine attempts a match A flow showing a pattern compiled to a state machine, a greedy quantifier consuming input, a test of the remaining pattern, and a feedback loop that hands back one character and retries. Your pattern ^(a+)+$ Compiled state machine Try at index 0 parse run Greedy step: take every "a" it possibly can step Does the rest of the pattern still match? then test Return the match Hand back one character, then try again yes no retry

Mechanism as implemented by backtracking engines including Python's re and PCRE2, checked 24 November 2026.

Four engines matter for the work you are probably doing, and they are not interchangeable.

Which engine is under your tool

Learn the engine, not the product. The syntax you can use follows from it.

PCRE2
The flavour behind Excel's REGEXTEST, REGEXEXTRACT and REGEXREPLACE, per Microsoft's own function reference
RE2
The library GoogleSQL uses for BigQuery regex functions, which rules out lookahead and lookbehind
Postgres 15
The release that added regexp_like, regexp_count, regexp_instr and regexp_substr
Python 3.11
The release that added atomic groups and possessive quantifiers to the re module

Sources: Microsoft's REGEXREPLACE function page, Google's BigQuery string function documentation, the PostgreSQL 15 feature matrix and the Python 3.11 release notes. Checked 24 November 2026.

Regex Cheat Sheet: The 24 Pieces of Syntax You Need

Learn these and you can read almost any pattern you will meet in a code review. The examples use Python syntax, which is close enough to PCRE2, Java and JavaScript to transfer.

Pattern What it means Example Matches
. Any character except a newline a.c abc, a7c, not ac
\d \w \s Digit, word character, whitespace \w+@\w+ rhea@acme
\D \W \S The negation of each of the above \D+ Any run with no digits
[abc] Any one of these characters [6-9]\d{9} An Indian mobile number
[^abc] Any character except these [^,]+ One CSV field
^ and $ Start and end of the string ^INV\d{6}$ INV004213 only, whole string
\b Word boundary, matches no character \bGST\b GST, not GSTIN
* Zero or more, greedy ab* a, ab, abbb
+ One or more, greedy \d+ 7, 42, 900
? Zero or one, makes it optional colou?r color, colour
{m,n} Between m and n repeats \d{4,6} A PIN code or an invoice run
*? +? ?? The lazy form, takes as little as possible <.+?> One HTML tag, not the whole line
*+ ++ ?+ Possessive, never hands characters back \d++abc Same matches, no backtracking
(...) Capturing group, numbered from 1 (\d{4})-(\d{2}) Year and month, separately
(?:...) Group without capturing (?:Mr|Ms)\.? Grouping with no extra output
(?P<name>...) Named group, readable in code (?P<pin>\d{6}) Reachable as m["pin"]
(?>...) Atomic group, discards backtrack points (?>\d+)x Fails fast instead of retrying
a|b Alternation, first alternative wins ^(?:GET|POST)\b An HTTP method at line start
(?=...) Lookahead, asserts without consuming \d+(?=\s*INR) The number before INR
(?!...) Negative lookahead ^(?!test_)\w+ Names that do not start with test_
(?<=...) Lookbehind, fixed width in Python (?<=INR\s)\d+ The number after INR
\1 Backreference to group 1 \b(\w+)\s\1\b A doubled word, the the
(?i) Inline flag, here case insensitive (?i)^gstin GSTIN, gstin, Gstin
\. and \\ Escape a metacharacter \d+\.\d{2} 1499.00, a real decimal point

Greedy against lazy, which is the mistake you will make most

Here is the difference drawn, because it produces more broken extractions than anything else on this page. Same subject string, one character of difference in the pattern.

Greedy: <.+>

Takes everything to the last > on the line, so you get one useless match.

A greedy quantifier matching an entire line of HTML The pattern with a greedy plus matches the whole string from the first angle bracket to the last, producing a single match. Subject and match span <b>hi</b> and <i>yo</i> 1 match Span covers all 23 characters

Verified in Python 3.11 on 24 November 2026.

Lazy: <.+?>

Stops at the first >, which is what you wanted all along.

A lazy quantifier matching each HTML tag separately The pattern with a lazy plus matches each of the four angle bracket tags separately instead of the whole string. Subject and match spans <b>hi</b> and <i>yo</i> 4 matches One span per tag, text left alone

Verified in Python 3.11 on 24 November 2026.

Python Regex Examples: 16 Patterns Worth Keeping

These are the patterns the insurer's team put in a shared patterns.py, and they are the second half of your 40. Compile them once at module level; compiling inside a loop over a million rows is a measurable waste.

Task Pattern Note
Indian mobile number ^(?:\+?91[\s-]?|0)?([6-9]\d{9})$ Group 1 gives the clean 10 digits
Indian PIN code ^[1-9][0-9]{5}$ Cannot start with zero
PAN ^[A-Z]{5}\d{4}[A-Z]$ Five letters, four digits, one letter
GSTIN ^(?:0[1-9]|[12]\d|3[0-8])[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$ State code 01 to 38, then the PAN
Email, pragmatic version ^[^@\s]+@[^@\s]+\.[A-Za-z]{2,}$ Good enough, and it cannot blow up
IPv4, loosely ^(?:\d{1,3}\.){3}\d{1,3}$ Range check the octets in code
ISO date ^(\d{4})-(\d{2})-(\d{2})$ Then hand it to a date parser
Rupee amount (?:INR|Rs\.?|₹)\s?([\d,]+(?:\.\d{2})?) Strip the commas afterwards
Trailing whitespace [ \t]+$ Use with the multiline flag
Repeated whitespace \s{2,} Replace with a single space
Doubled word \b(\w+)\s+\1\b Catches copy and paste errors in free text
Everything inside quotes "([^"]*)" Negated class, not .+?, so it cannot run away
Named capture of a log line ^(?P<ip>\S+) \S+ \S+ \[(?P<ts>[^\]]+)\] Access by name, not by index
Number before a unit \d+(?=\s*(?:GB|TB)) Lookahead, the unit is not consumed
Exclude a prefix ^(?!tmp_|test_)[a-z_]+$ Negative lookahead as a filter
Split on commas outside quotes Do not. Use csv.reader The honest entry in the table

Put together, extraction looks like this. The whole snippet runs on a stock Python 3.11 install with no packages.

import re

PHONE = re.compile(r"^(?:\+?91[\s-]?|0)?([6-9]\d{9})$")
GSTIN = re.compile(r"^(?:0[1-9]|[12]\d|3[0-8])[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$")

def clean_phone(raw: str) -> str | None:
    squeezed = raw.replace(" ", "").replace("-", "")
    m = PHONE.match(squeezed)
    return m.group(1) if m else None

for raw in ["+91 98765 43210", "09876543210", "98765-43210", "1234567890"]:
    print(raw, "->", clean_phone(raw) or "REJECT")

# +91 98765 43210 -> 9876543210
# 09876543210     -> 9876543210
# 98765-43210     -> 9876543210
# 1234567890      -> REJECT

That last line is the point. 1234567890 is ten digits and sails through a len(x) == 10 check, but no Indian mobile number starts with a 1, so [6-9] rejects it. The insurer's export held about nine thousand of those, mostly placeholders typed by agents in a hurry.

In pandas the same patterns drop into str.extract and str.match, covered in our Pandas cheat sheet for 2026. Also read: the SQL commands cheat sheet if you would rather clean in the warehouse than in Python.

SQL Regex Pattern Matching: Postgres, BigQuery, Excel and Power BI

This is where portable patterns stop being portable. One expression can work in Python, error in BigQuery and behave differently again in Postgres.

You want to Python re PostgreSQL 15 and later BigQuery (RE2) Excel 365
Test whether it matches re.search regexp_like(col, pat) REGEXP_CONTAINS(col, pat) REGEXTEST(A2, pat)
Pull out one piece m.group(1) regexp_substr(col, pat, 1, 1, '', 1) REGEXP_EXTRACT(col, pat) REGEXEXTRACT(A2, pat)
Replace re.sub regexp_replace(col, pat, repl, 'g') REGEXP_REPLACE(col, pat, repl) REGEXREPLACE(A2, pat, repl)
Count occurrences len(re.findall(...)) regexp_count(col, pat) ARRAY_LENGTH(REGEXP_EXTRACT_ALL(...)) No direct equivalent
Use lookahead or lookbehind Yes Yes No, RE2 does not support it Yes, PCRE2
Capture groups in an extract Any number Pick with the group argument Exactly one, or it errors Pick with the arguments
Case insensitive re.I ~* or the 'i' flag (?i) inline The case_sensitivity argument
Guaranteed against blowups No, it backtracks No, it backtracks Yes, that is RE2's whole point No, PCRE2 backtracks

Two rows deserve more than a cell. BigQuery's REGEXP_EXTRACT errors outright when a pattern has two or more capturing groups, which catches everyone pasting a working Python pattern into the console. And the last row is the reason RE2 exists: it compiles to an automaton and matches in time linear in the input, so it cannot be made to hang, at the cost of giving up lookaround entirely. For a query engine running patterns written by thousands of analysts, that is the right trade.

If your day spans Excel, SQL, Python and Power BI rather than one of them, a live Data Analyst course covering all four with PL-300 preparation is where these flavour differences get practised on real datasets instead of read about. Spark's regexp_extract follows Java's syntax, one more flavour again, and it is part of 360DT's Microsoft Fabric data engineering program.

Catastrophic Backtracking: The Shape That Took Cloudflare Down

On 2 July 2019, Cloudflare went down globally. Its postmortem attributes the failure to one managed WAF rule whose regular expression caused excessive backtracking, driving CPU to saturation on every core handling HTTP and HTTPS traffic across the network. The engine was PCRE, which has no ceiling on backtracking steps. One rule, deployed everywhere at once, and a company serving a large slice of the internet stopped serving it.

The shape to recognise is a quantifier nested inside another quantifier where both can match the same characters. (a+)+ is the teaching example. (\s*.*)+, (\w+\s?)* and (.*=.*)+ are the ones you will write without noticing. Here is the cost, measured; run it yourself and you will get the same curve.

import re, time

pat = re.compile(r"^(a+)+$")
for n in (16, 20, 24, 28):
    s = "a" * n + "b"          # the trailing b guarantees failure
    t = time.perf_counter()
    pat.search(s)
    print(n, round(time.perf_counter() - t, 4), "s")

# 16 0.0025 s
# 20 0.0419 s
# 24 0.6389 s
# 28 10.5094 s

Time to fail on (a+)+ by input length

Every extra character doubles the work. Twelve more characters is four thousand times the time.

16 charsstill feels instant
2.5 msmeasured
20 charsa slow unit test
41.9 msmeasured
22 charsnoticeable lag
164 msmeasured
24 charsa visible stall
639 msmeasured
26 charsrequest timeout
2.59 smeasured
28 charsthe pinned core
10.5 smeasured

Measured with the snippet above on Python 3.11.18, 24 November 2026. Bar length is on a log scale, because a linear one would make the first four bars invisible.

Now the fix, which most write-ups leave out. Make the inner quantifier possessive so it never hands characters back:

import re, time

s = "a" * 28 + "b"
for p in (r"^(a+)+$", r"^(a+)++$", r"^a+$"):
    pat = re.compile(p)
    t = time.perf_counter()
    pat.search(s)
    print(p, round((time.perf_counter() - t) * 1000, 4), "ms")

# ^(a+)+$    10509.4    ms
# ^(a+)++$        0.0019 ms
# ^a+$            0.0009 ms

That is 10.5 seconds down to two microseconds for an identical set of matches, using a feature the Python 3.11 release notes added to the standard library. The third line is the better answer anyway: the nesting was never needed, and ^a+$ accepts exactly the same strings. The pattern that blows up is nearly always more complicated than the problem required.

What usually goes wrong here
  • You test on clean data. Catastrophic patterns match fine on valid input. They only explode on input that fails, which is exactly what arrives in production.
  • You use .* as a separator. Between two things you care about, prefer a negated class: [^,]* or [^"]* cannot overlap with its neighbours, so it cannot backtrack into them.
  • You accept a pattern from a user. A search box that passes input to re.compile is a denial of service endpoint. Use RE2 through the google-re2 bindings, or escape the input with re.escape and treat it as literal text.
  • You have no timeout. Python's re has no timeout parameter, so run untrusted matching in a worker process you can kill, not in your request thread.

Here is the honest caveat. Regex is a genuinely bad tool for anything nested. HTML, JSON, YAML, balanced brackets and quoted CSV have structure a regular language cannot describe, and every pattern you write for them is a pile of special cases that works until the day it does not. Use csv.reader, json.loads, an HTML parser. Reach for regex when the text is flat and line shaped: log lines, identifiers, codes, free text fields. That is most of a data job. It is not all of it.

Live course

Learn the cleaning work that regex is only one part of, live

Live online·Sat–Sun, 8–11 PM IST·10 weeks·Rs 24,999

Excel, SQL, Python and Power BI taught live across ten weekends, with preparation for the Microsoft PL-300 certification. Hands on projects, mentor support and placement guidance are included.

Explore the course
Data Analyst Course: Excel, SQL, Python & Power BI (PL-300)

A Worked Example: Validating a Policyholder Export End to End

Back to the insurer. Two analysts, one CSV of 1.2 million policy rows, four columns that are meant to be identifiers and are not. Here is the whole job, reproducible on any file with the same shape.

Step 1. Write the fixtures first. Five values you know are valid, five you know are not. For GSTIN, 27AAPFU0939F1ZV and 07AAACH7409R1ZZ pass; 00AAPFU0939F1ZV (no state code 00), 39AAPFU0939F1ZV (state codes stop at 38) and lowercase 27aapfu0939f1zv must fail. Each was checked against the table pattern before any cleaning code got written.

Step 2. Parse, do not validate twice. One pass that tests and extracts together, with named groups so downstream code reads like English:

LOG = re.compile(
    r"^(?P<ip>\S+) \S+ \S+ \[(?P<ts>[^\]]+)\] "
    r'"(?P<method>[A-Z]+) (?P<path>\S+) [^"]*" '
    r"(?P<status>\d{3}) (?P<bytes>\d+)$"
)
m = LOG.match(line)
if m:
    row = m.groupdict()   # {'ip': '203.0.113.9', 'method': 'GET', ...}

Note what carries the load: [^\]]+ and [^"]*, not .+?. A negated class cannot overlap the delimiter that follows it, so this pattern has no backtracking to do even on a malformed line. That one habit is worth more than every optimisation trick on this page.

Step 3. Count what you rejected, then look at it. The first run rejected 11% of phone numbers. Instead of loosening the pattern, they printed the top twenty rejected values: nine thousand were 1234567890, and about four hundred were real numbers with a +91 (0) prefix the pattern disallowed. They fixed the pattern for the four hundred and raised a data quality ticket for the rest. A rejection rate is a finding, not a bug in your regex.

Step 4. Pin it with a test. The step one fixtures become a test file, so when someone widens the pattern in six months to let one odd vendor through, the test says what else they just let in.

Also read: SQL query optimization in 2026, because a regexp_like in a WHERE clause will not use an index and is usually the next thing to get slow.

Where This Regex Cheat Sheet Earns Its Keep at Work

Three places, concretely. In analytics, regex is how a free text field becomes a dimension you can group by, and REGEXEXTRACT in Excel means you no longer need a column of nested MID and FIND calls to get there. In platform and DevOps work it is how log lines become metrics, which is most of what a CloudWatch Logs Insights or Loki query does, and it sits beside the Linux and shell tooling in the AWS Solutions Architect and DevOps course.

In AI engineering it is load bearing again: redacting PII before text reaches a model, checking that output matches the schema you asked for, and writing the deny patterns in a guardrail layer are all regex jobs, built and tested live in 360DT's AI Engineer course. Structured extraction with Azure AI services, where the regex and the model each do half the task, is part of the Generative AI Developer programme. To see any of this taught before paying, sit in on a free webinar or book a demo class; the full certifications overview shows which exam each track maps to.

One more thing, since it is the obvious question. An LLM will write a working regex from a sentence faster than you will, and for a one-off extraction you should let it. What it will not reliably tell you is that the pattern it just produced has a nested quantifier that hangs on malformed input, or that its lookbehind will be rejected by BigQuery. Reading regex is now the valuable half of the skill.

Take the habit rather than the syntax: write five bad inputs before you write the pattern, and prefer a negated character class to a dot star every time. Those two moves would have saved the insurer's stalled job. In your position I would spend one evening on the 24 syntax rows until you can read them without looking, keep this page open for the rest, and let a model draft the one-off patterns. If regex is the first gap you have found in your data work and probably not the last, the Data Analyst course covers the whole pipeline it belongs to, and a free webinar is the cheapest way to see whether the teaching suits you.

Frequently asked questions

What is a regex cheat sheet and how should I actually use one?

It is a reference to the metacharacters, quantifiers, groups and flags a regex engine understands. Use it to read patterns rather than assemble them from scratch: hold the 24 core syntax rows in memory, and look up the ready-made patterns and flavour differences as needed.

Is regex the same in Python, SQL and Excel?

No. Python and Excel are close, since Excel's REGEXTEST, REGEXEXTRACT and REGEXREPLACE use the PCRE2 flavour per Microsoft's documentation. PostgreSQL has its own POSIX based engine and only added regexp_like, regexp_count, regexp_instr and regexp_substr in version 15. BigQuery uses RE2, which rejects lookahead and lookbehind outright.

What is the difference between greedy and lazy quantifiers?

A greedy quantifier such as .+ takes as much as it can and gives characters back only when forced. A lazy one, .+?, takes as little as possible and grows only when forced. On the string <b>hi</b> and <i>yo</i>, the pattern <.+> returns one match spanning all 23 characters, while <.+?> returns four, one per tag.

Why is my regex so slow on long strings?

Almost certainly catastrophic backtracking from a quantifier nested inside another quantifier, such as (a+)+ or (\w+\s?)*. On our Python 3.11 run, ^(a+)+$ took 2.5 ms to fail on 16 characters and 10.5 seconds on 28, doubling with each extra character. Flatten the nesting, or make the inner quantifier possessive with ++.

How do I validate an Indian mobile number or a GSTIN with regex?

For a mobile number, ^(?:\+?91[\s-]?|0)?([6-9]\d{9})$ after stripping spaces and hyphens; it also rejects placeholders like 1234567890, since no real number starts with a 1. For GSTIN, ^(?:0[1-9]|[12]\d|3[0-8])[A-Z]{5}\d{4}[A-Z][1-9A-Z]Z[0-9A-Z]$ checks the state code, embedded PAN and fixed Z. Neither replaces a checksum check.

Can I use lookbehind in Python and in a data warehouse?

In Python yes, but only fixed width: (?<=INR\s)\d+ is fine, (?<=INR\s*)\d+ raises an error. PostgreSQL supports lookbehind. BigQuery does not support it at all, because RE2 gives up lookaround in exchange for a guarantee that no pattern can hang the engine.

Is regex still worth learning when an AI can write it for me?

Yes, but for a narrower reason than before. A model will draft a correct pattern for a one-off job faster than you can, and you should let it. It will not reliably warn you that the pattern has a nested quantifier that hangs on malformed input, or a lookbehind your warehouse rejects. Learn to read and review regex; delegate the drafting.

What is the best way to practise regex?

Take a messy column from work, write five valid and five invalid examples, then write the pattern that separates them and run it with re.findall so you see every match. Practise on failing input, because that is where the bugs and the performance cliffs live.

About this guide. 360 Digital Transformation is an Anthropic Partner and a Microsoft Authorized Training Partner. Other certification bodies, vendors and employers named here are not affiliated with us. Tools and versions change quickly; commands and figures cited were checked on 24 November 2026.

Learn it live with 360 Digital Transformation

Turn this guide into a skill employers can see

Live weekend cohortEMI available

Data Analyst Course: Excel, SQL, Python & Power BI (PL-300)

Rs. 24,999

Tools and platforms you work with

  • Microsoft Excel
  • PostgreSQL
  • MySQL
  • Python
  • pandas
  • NumPy
  • matplotlib and seaborn
  • Jupyter
Add bonus modules
See the syllabus and batch dates

Other live courses on this career path