Free online tool

Upload a file

Drop your file hereTap to choose a file

or click to browse, or paste from the clipboard

← Back to Blog

Regex Cheat Sheet with Examples: Syntax, Flags and Common Patterns

A regex cheat sheet is a quick reference for regular expression syntax: \d matches a digit, \w a letter, digit or underscore, . any character except a line break, + repeats the item before it one or more times, and ^ and $ pin a pattern to the start and end of the text. The tables below cover the syntax JavaScript, Python, PHP, Java, C# and Go share, then give common patterns for email addresses, URLs, phone numbers and dates, each with strings it matches, rejects and gets wrong. To build a pattern from your own examples, or to see what an unfamiliar one means, paste it into the Regex Generator.

Regex cheat sheet: core syntax

These tokens work the same way in all six languages, apart from the differences further down. MDN's regular expressions guide has the full JavaScript reference.

Characters and classes

Token Matches Example
. Any character except a line break c.t matches cat, c9t, c-t
\d A digit \d{3} matches 404
\w A letter, digit or underscore \w+ finds user_42 in user_42!
\s A space, tab or line break a\sb matches a b
\D \W \S Anything except \d, \w, \s \D+ finds abc in abc123
[abc] [a-z] One listed character, or one in a range gr[ae]y matches gray, grey
[^abc] One character not listed [^0-9] matches any non-digit
\t \n \r Tab, line feed, carriage return \r?\n matches a Windows or Unix line break

These characters have special meanings and need a backslash to match literally: . ^ $ * + ? ( ) [ ] { } | \. Inside square brackets most of them lose their meaning, so [.?] matches a dot or a question mark.

Anchors and boundaries

Token Matches at Example
^ The start of the text, or of each line with the m flag ^Hello matches Hello world, not Say Hello
$ The end of the text, or of each line with m world$ matches Hello world
\b A word boundary \bcat\b finds cat in the cat sat, not in category
\B Anywhere except a word boundary \Bcat finds cat in concat, not in cat

Quantifiers

Token Repeats the item before it Example
* Zero or more times ab*c matches ac, abc, abbc
+ One or more times ab+c matches abc and abbc, not ac
? Zero or one time colou?r matches color, colour
{3} Exactly 3 times \d{3} matches 404
{2,4} 2 to 4 times \d{2,4} finds 1234 in 12345
{2,} 2 or more times \d{2,} matches 12 and 123456
*? +? As few times as possible (lazy) <.+?> finds <b>, not all of <b>bold</b>

Groups and alternation

Token Meaning Example
(abc) Capture group (\d{4})-(\d{2}) captures 2026 and 11 from 2026-11
(?:abc) Group that does not capture (?:ab)+ matches ababab
(?<year>abc) Named group (?<year>\d{4}) captures 2026 as year
\1 The same text as group 1 (\w)\1 finds ll in hello
a|b Either side cat|dog matches cat or dog

Lookahead and lookbehind

Lookarounds check the text next to a match without including it.

Token Meaning Example
(?=abc) Followed by abc \d+(?=%) finds 50 in 50% off
(?!abc) Not followed by abc q(?!u) finds the q in Iraq, not in quit
(?<=abc) Preceded by abc (?<=\$)\d+ finds 25 in $25
(?<!abc) Not preceded by abc (?<!\$)\b\d+ finds 30, not 25, in $25 or 30

Regex flags in each language

Flags change how the whole pattern behaves. JavaScript writes them after the closing slash, as in /cat/gi, and PHP after its closing delimiter, as in /cat/i (the PHP manual lists them all). Python, Java and C# take an option, and Go uses inline flags.

Language Ignore case ^ $ per line . matches newline Find every match
JavaScript i m s g with matchAll()
Python re.I re.M re.S re.finditer()
PHP i m s preg_match_all()
Java CASE_INSENSITIVE MULTILINE DOTALL Loop on find()
C# IgnoreCase Multiline Singleline Regex.Matches()
Go (?i) (?m) (?s) FindAllString()

Python's long names are re.IGNORECASE, re.MULTILINE and re.DOTALL; the Java constants belong to Pattern and the C# ones to RegexOptions. Every language here except JavaScript also accepts an inline flag such as (?i) at the start of a pattern. JavaScript has only the scoped form (?i:abc), supported in current browsers since 2025.

Common regex examples and what they get wrong

Each pattern below is in the Regex Generator's Common patterns list unless noted, with sample lines that should and should not match. Patterns check the format, not whether a value is real.

Regex for email addresses

^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$

This matches jane.doe@example.com and sales+eu@shop.co.uk, and rejects jane@example, jane doe@example.com and @example.com. It also accepts the invalid double dot in jane..doe@example.com, and rejects rare but valid forms such as "jane doe"@example.com, jane@[192.0.2.1] and josé@example.com.

Browsers check type="email" fields with this pattern (not in the list) from the HTML standard, which deliberately departs from the email RFCs:

^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$

It allows every symbol an unquoted address may contain and limits domain labels to 63 characters with no hyphen at either end, but it accepts jane@localhost. Only a confirmation email proves that an address works.

URLs

^https?:\/\/[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+(?::\d{1,5})?(?:[\/?#][^\s]*)?$

Use it with the i flag. It matches https://example.com and http://sub.example.org:8080/path?q=1#top, and rejects ftp://example.com, https://localhost and example.com. It also accepts the impossible port 99999 and rejects IPv6 hosts such as http://[::1]/ and non-ASCII domains such as https://bücher.example. In code, parse the URL with new URL() in JavaScript or urllib.parse.urlsplit() in Python, then check the scheme and host.

Phone numbers

^(?:\+1[\s.-]?)?\(?[2-9]\d{2}\)?[\s.-]?\d{3}[\s.-]?\d{4}$

For US numbers, this matches (555) 123-4567, +1 555.123.4567 and 5551234567, and rejects 123-456-7890 and 555-1234. Each bracket is optional on its own, so (555 123-4567 passes too. For other countries, strip spaces and punctuation and check the E.164 form with ^\+[1-9]\d{6,14}$, or use a library such as Google's libphonenumber.

Dates and times

^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$

This checks ISO dates: it matches 2026-11-25 and rejects 2026-13-01, 2026-1-5 and 25-11-2026. It does not know month lengths, so 2026-02-31 and 2025-02-29 pass. Check the calendar in code: Python's date.fromisoformat() rejects both, but in Node.js new Date("2026-02-31") quietly rolls over to March 3 (UTC). For 24-hour times, ^(?:[01]\d|2[0-3]):[0-5]\d$ matches 09:30 and 23:59 but not 24:00 or 9:30.

IP addresses

^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$

This matches 192.168.1.1 and 255.255.255.255, and rejects 256.1.1.1, 192.168.1 and the leading zero in 01.2.3.4. In Python code, ipaddress.ip_address() validates IPv4 and IPv6 without a regex.

Numbers, passwords and IDs

  • Numbers: ^-?(?:\d+(?:\.\d+)?|\.\d+)$ matches 3.14, -0.5 and .75 but not 1,000 or 1e5. For grouped thousands such as 12,345,678.90, use ^-?\d{1,3}(?:,\d{3})*(?:\.\d+)?$. Neither reads European formats such as 1.234,56.
  • Password rule: ^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{12,}$ uses one lookahead per character type, so it rejects the 28-character passphrase correct horse battery staple. NIST's password guidelines tell services not to impose composition rules like these; the guide to strong passwords explains why length matters more.
  • UUID: with the i flag, ^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ accepts versions 1 to 8 but rejects the nil (all zeros) and max (all f) UUIDs, which RFC 9562 also defines.
  • Base64: ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$ rejects unpadded and URL-safe text, and it matches an empty string. The Base64 Encoder/Decoder shows what a value contains.

Regex differences between JavaScript, Python, PHP, Java, C# and Go

The syntax above is shared, but these differences break patterns copied from one language to another:

Language Named group Lookbehind \d and \w $ before a final newline
JavaScript (?<y>…) Any length ASCII only No
Python (?P<y>…) Fixed length Unicode Yes
PHP (?<y>…) or (?P<y>…) Fixed or bounded ASCII, Unicode with u Yes
Java (?<y>…) Most forms ASCII by default Yes
C# (?<y>…) Any length Unicode Yes
Go (?P<y>…), or (?<y>…) from Go 1.22 None ASCII only No
  • Unicode digits. In Python and C#, \d also matches digits from other scripts, so ^\d{5}$ accepts ١٢٣٤٥ as a ZIP code. Use [0-9], or re.ASCII in Python and RegexOptions.ECMAScript in C#.
  • A trailing newline. In Python, PHP, Java and C#, $ also matches before a newline at the very end, so ^\d+$ accepts "123\n". Anchor with \z (\Z in Python), or use Python's re.fullmatch() or Java's matches().
  • Match versus search. Python's re.match() anchors only at the start and Java's String.matches() needs the whole string, while JavaScript's test() and Go's MatchString() search anywhere.
  • Lookarounds. Go has no lookarounds or backreferences, so (?<=\$)\d+ fails to compile there; capture with \$(\d+) instead. PHP needs a lookbehind with a maximum length, so no * or + inside it, and Java rejects a repeated group inside one, such as (?<=(?:ab)+).
  • Unicode letters. \p{L} works in Java, C# and Go, and in PHP and JavaScript with the u flag; without u, JavaScript reads it as the literal text p{L}. Python's re has no \p{…}; [^\W\d_] matches one letter instead.
  • Replacements. Group 1 is $1 in every language here except Python, which uses \1. Named groups are $<y> in JavaScript, \g<y> in Python and ${y} in Java, C# and Go. In Go, $1x means a group named 1x, so write ${1}x.

Official references: Python's re module, Java's Pattern class, the .NET quick reference and Go's regexp/syntax. The Regex Generator's code panel converts named groups for Python and adds a warning to Go code that uses lookarounds or backreferences, but it leaves \d, $ and \p{L} as written, so these points still apply.

How to build and test a regex with Zutilium

  1. Open the Regex Generator. Under Start from, choose My examples to generate a pattern, or Common patterns to load one of 35 ready-made ones, including most of those above.
  2. Paste values to accept into Text that should match, one per line, and a few near misses into Text that should not match.
  3. Under The pattern should match, choose The whole value (for validation) to wrap the pattern in ^ and $, or Inside longer text (for searching) to use word boundaries. Tick Ignore upper and lower case if case doesn't matter.
  4. Pick a suggestion. Each shows how many of your examples it matches and rejects, and one that fits them all is marked (recommended). What this regex means explains every part in plain English.
  5. Paste real data into Test text. Test each line on its own checks every line as a separate value, as a form validator would; untick it to search the whole text, and tick the g flag to find every match.
  6. Under Use it in code, choose a Language and select Copy code, or Copy regex for the bare pattern.

With the sample order numbers the page opens with, the Balanced suggestion is ^ORD-\d{4}-\d{4}$, scored "Matches 3 of 3 · rejects 2 of 2", and the tester reports "3 of 5 lines have a match · 3 matches in total." Everything runs in your browser, so nothing you paste is uploaded.

How to test a regex before you use it

Try values that must match, near misses that must fail (one character too few or too many, the wrong separator, an extra character at either end) and edge cases: an empty string, surrounding spaces, a trailing newline and digits from other scripts. Run them in the language that will use the pattern, because its rules may differ from the tester's. In Python:

import re

zip_code = re.compile(r"\d{5}(?:-\d{4})?", re.ASCII)
assert all(zip_code.fullmatch(s) for s in ["90210", "10001-1234"])
assert not any(zip_code.fullmatch(s) for s in ["9021", "902101", "90210-12", "90210\n", "١٢٣٤٥"])

Without re.ASCII, the last assertion fails, because \d accepts ١٢٣٤٥.

Catastrophic backtracking

A repeat inside a repeat, such as ^(a+)+$, can take exponentially long to fail. On a run of the letter a followed by an exclamation mark, JavaScript, Python and C# (without RegexOptions.NonBacktracking) try every way to split the letters between the two + before giving up, so each extra letter doubles the time.

Remove the nested repeat (^a+$ matches the same text), or make the inner one atomic with (?>a+) or a++ in Python 3.11 and later, PHP and Java; C# has (?>a+), match timeouts and RegexOptions.NonBacktracking. Go's engine runs in linear time, the trade-off for having no lookarounds or backreferences. The Regex Generator's tester stops a pattern after 1.5 seconds with "This pattern took too long on the test text", so the page never freezes.

Troubleshooting

It works in the tester but not in your code

Usually the string literal ate the backslashes: in JavaScript, new RegExp("\d+") becomes d+, and Java refuses to compile "\d+". Double the backslashes, or use a regex literal /\d+/ in JavaScript, a raw string r"\d+" in Python, a verbatim string @"\d+" in C# or a backquoted string in Go; Copy code in the Regex Generator does this for you. Also check the flags, because a pattern copied on its own leaves i or m behind.

Error: nothing to repeat

A quantifier has nothing in front of it, often because a file glob such as *.txt was used as a regex. The message varies: "Nothing to repeat" in JavaScript, "nothing to repeat at position 0" in Python, "Dangling meta character ''" in Java, "Quantifier '' following nothing" in C# and "missing argument to repetition operator" in Go. The regex for names ending in .txt is ^.*\.txt$. In a cron schedule, the asterisk means every value, as the cron expression examples show.

It matches too much

Quantifiers are greedy, so ".*" in say "hi" and "bye" runs from the first quote to the last. Use the lazy ".*?", or better, "[^"]*", which cannot cross a closing quote. For values inside JSON or HTML, use a parser, because no regex handles nesting reliably; the JSON Formatter shows a document's structure.

test() returns true, then false

In JavaScript, a regex with the g flag stores where its last match ended in lastIndex, so calling test() twice on the same string returns true and then false. Leave g off for yes-or-no checks, or reset lastIndex to 0.

Frequently asked questions

What does .* mean in regex?

. matches any character except a line break and * repeats it zero or more times, so .* matches any run of characters on one line, including none. Add the s flag (re.S in Python) to let it cross line breaks.

What does ?: mean in regex?

(?:…) is a non-capturing group. It groups part of a pattern, as in (?:jpg|png) or (?:ab)+, without creating a numbered group, so \1 and $1 still point to the groups you care about.

How do I match a literal dot or bracket?

Put a backslash before it: \. matches a dot and \[ an opening bracket. To escape user input for a pattern, use re.escape() in Python, preg_quote() in PHP, Pattern.quote() in Java, Regex.Escape() in C#, regexp.QuoteMeta() in Go or RegExp.escape() in JavaScript, which current browsers have supported since 2025.

How do I match a newline in regex?

Use \n for a line feed, or \r?\n to accept Windows line endings too. A . skips line breaks unless you add the s flag (re.S in Python), while [\s\S] matches any character, line breaks included, in every language here. To make ^ and $ work line by line, add the m flag.

How does a regular expression generator work?

It compares your examples, keeps what they share, turns the parts that vary into classes such as \d{4} and tests each candidate against your matching and non-matching examples. It can only generalize from what you give it: from jane.doe@example.com, sales+eu@shop.co.uk and bob@test.org, Zutilium's Regex Generator suggests ^[a-z.+]{3,}@[a-z]{4,}\.[a-z.]{3,}$, which rejects any address with a digit or a capital letter. Add varied examples, or start from a tested pattern.