Regex cheat sheet: syntax plus 30 tested patterns

By Hammad Rasool · November 11, 2026

Quick answer: the syntax table below covers the regex you need for almost every task, and the 30 patterns after it are ready to copy for validating input (email, phone, date, IPv4, UUID, CNIC) or pulling things out of text. Every pattern was run against strings it should and shouldn't match. Paste one into the regex tester with your own data before you use it: the cheat sheet tells you what a pattern does, your data tells you whether that's what you need.

How this was tested: on 11 November 2026 each pattern was run in JavaScript (Node.js 24.18.1, the same V8 engine as Chrome) against the example strings shown, and every result matched what the table says. The same patterns were then run with Python 3.12's re module: 29 behaved the same and one would not compile (named groups, see the differences table). PCRE, Java and .NET were not tested.

Regex syntax cheat sheet

TokenMeaning
.Any character except a line break (add the s flag to include line breaks)
\d \w \sDigit, word character (letter, digit, _), whitespace
\D \W \SThe opposite of each
\bWord boundary: between a word character and anything else
^ $Start and end of the string (of each line with the m flag)
[abc] [a-z]One character from the set or range
[^abc]One character not in the set
a|ba or b
( )Capturing group, reused as \1 or $1
(?: )Group without capturing
(?<name> )Named group (JavaScript); Python writes (?P<name> )
* + ?0 or more, 1 or more, 0 or 1
{3} {2,5} {2,}Exactly 3, 2 to 5, 2 or more
*? +? ??Lazy versions: match as little as possible
(?= ) (?! )Followed by / not followed by (lookahead)
(?<= ) (?<! )Preceded by / not preceded by (lookbehind)
\. \* \(A literal dot, star, bracket: escape special characters
\p{L} \p{N}Any letter / number in any script (JavaScript with the u flag)

Flags

FlagEffect
gFind every match, not just the first
iIgnore case
m^ and $ match at every line
sDot matches line breaks too
uUnicode mode: enables \p{...} and stricter syntax

20 patterns for validating input

These are anchored with ^ and $, so the whole value must match. Without the anchors, \d+ would accept abc123 because part of it matches.

PurposePatternMatchesRejects
Digits only/^\d+$/2026, 0012312a, -5, empty
Integer, optional sign/^[+-]?\d+$/42, -7, +04.2, --1
Decimal number/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/3.14, -0.5, .5, 7.1.2.3, 1e5, .
Thousands separators/^\d{1,3}(?:,\d{3})*(?:\.\d+)?$/1,234, 12,345,678.901234,567, 12,34
Hex colour/^#(?:[0-9a-fA-F]{3}){1,2}$/#fff, #4F46E5#ffff, 4F46E5
Email (practical check)/^[^\s@]+@[^\s@]+\.[^\s@]+$/sara@example.com, a.b+tag@mail.co.uksara@, sara@localhost
Username (3 to 16)/^[A-Za-z0-9_]{3,16}$/sara_k, user2026ab, sara-k
Password: upper, lower, digit, symbol, 8+/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/Str0ng!passweakpass, NoDigits!, Sh0rt!
Date YYYY-MM-DD (shape)/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/2026-11-112026-13-01, 2026-1-5
Time HH:MM, 24-hour/^(?:[01]\d|2[0-3]):[0-5]\d$/00:00, 23:5924:00, 9:30, 12:60
IPv4 address/^(?:(?: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)$/192.168.1.1, 255.255.255.255256.1.1.1, 01.2.3.4
http/https URL/^https?:\/\/[^\s/?#]+(?:[/?#]\S*)?$/https://toolstash.tools, http://localhost:3000/a?b=1ftp://x.com, https://
URL slug/^[a-z0-9]+(?:-[a-z0-9]+)*$/format-plsql-tsql-start, double--dash, Upper
UUID (v1 to v8)/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ia v4 and a v7 UUIDno dashes, version digit 0
Semantic version/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/1.2.3, 2.0.0-rc.1+build.51.2, 01.2.3, v1.2.3
Pakistan mobile number/^(?:\+92|0092|0)3\d{9}$/03001234567, +9230012345670300-1234567, 0421234567
Pakistan CNIC/^\d{5}-\d{7}-\d$/35202-1234567-13520212345671
US ZIP code/^\d{5}(?:-\d{4})?$/10001, 10001-12341000, 10001-12
Image file name/\.(?:jpe?g|png|gif|webp)$/iphoto.JPG, a.b.webpphoto.jpg.exe
Blank line/^\s*$/empty, spaces, a tab" x "

What these patterns don't check

  • Dates: the date pattern checks the shape only. It accepted 2026-02-31 in the test. Parse the value with a date library to know whether the day exists.
  • Email: the email pattern is a sanity check, not a standard. It accepted a..b@x.com, which most mail servers reject. The only real test of an address is sending a confirmation email to it.
  • Phone and CNIC: the Pakistan patterns check the format (mobile numbers start with 3 after the country or trunk code and have 10 digits after the 0). They can't tell whether the number is in use. Strip spaces and dashes before testing a phone number.

10 patterns for finding things in text

These are not anchored and use the g flag, so they return every match in a longer text.

PurposePatternTextFound
Every number in a text/-?\d+(?:\.\d+)?/gPaid 1,250.50 on 2026-11-11 (-3 items)1 · 250.50 · 2026 · -11 · -11 · -3
Hashtags/#\w+/gShip it #release #v2_0 #2026!#release · #v2_0 · #2026
Repeated words/\b(\w+)\s+\1\b/giThis is is a test. The the end, then then.is is · The the · then then
Trailing spaces/[ \t]+$/gmlines ending in spaces or a tabthe spaces and the tab
Double-quoted strings/"(?:[^"\\]|\\.)*"/gx = "say \"hi\"" + "" + "a\\b""say \"hi\"" · "" · "a\\b"
key=value pairs/(\w+)=("[^"]*"|\S+)/glevel=info msg="disk full" code=507level=info · msg="disk full" · code=507
Lines with error but not debug/^(?!.*\bdebug\b).*\berror\b.*$/gmerror: disk / debug error: skip / all good / fatal error hereerror: disk · fatal error here
Each HTML tag (lazy)/<.+?>/g<b>bold</b> and <i>it</i><b> · </b> · <i> · </i>
Same, greedy/<.+>/g<b>bold</b> and <i>it</i>the whole text, one match
Date parts, named/(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/gfrom 2026-11-01 to 2026-11-302 matches; groups year 2026, month 11, day 01

Look at the first row before you reuse it: in that sentence the number pattern split 1,250.50 into 1 and 250.50, and read the dashes in the date as minus signs. A pattern that is right for one text can be wrong for the next, which is why testing on your real data matters more than the pattern itself.

Regex is fine for pulling simple tags out of a snippet, as in the HTML rows, but not for parsing whole HTML documents. Use the browser's DOMParser or a proper HTML parser for that.

JavaScript vs Python: differences found in testing

Most patterns move between the two languages unchanged. These didn't; every row is a test result, not a rule from a manual:

Pattern or featureJavaScriptPython 3.12
^\d+$ on Urdu digits ۲۰۲۶No matchMatch
^\w+$ on اردو or CaféNo matchMatch
#\w+ on #کراچیNo match#کراچی
^\d+$ on "123\n"No matchMatch ($ allows one final line break)
\p{L}Works with the u flagError: bad escape \p
(?<year>...)Named groupError: unknown extension ?<y
(?P<year>...)Error: Invalid groupNamed group
Lookbehind (?<=a+)xWorksError: look-behind requires fixed-width pattern
Use a group in a replacement$<d>/$<m>/$<y>\g<d>/\g<m>/\g<y>

The first three rows matter for any site with Urdu, Arabic or accented input. In JavaScript, \d and \w mean ASCII only. Python's re treats them as Unicode by default, so ^\d+$ accepted ۲۰۲۶, and saving that as a number elsewhere may fail. Add the re.ASCII flag in Python for ASCII-only digits (the test confirmed it then rejects Urdu digits). In JavaScript, use \p{L} and \p{N} with the u flag when you do want every script: /#[\p{L}\p{N}_]+/u matched #کراچی. One more catch: a letter typed with a separate accent mark (Unicode NFD form) failed ^\p{L}+$ and passed ^[\p{L}\p{M}]+$.

For Python's $, use \Z when the value must not end with a line break: ^\d+\Z rejected "123\n" in the test.

Three traps to avoid

1. A case-insensitive flag you didn't ask for

With the i flag, [A-Z] also matches lower case. The password pattern above then accepted weakpass1!, which has no capital letter, and the slug pattern accepted Upper. Use i only when case really doesn't matter. (The ToolStash regex tester used to start with i ticked; it now starts with only g, like a plain JavaScript regex, and has a u option for the Unicode patterns above.)

2. The g flag with test()

const re = /\d+/g;
re.test("42");   // true
re.test("42");   // false: the search started at lastIndex 2

A global regex remembers where the last match ended. Reusing one with test() gave true and then false for the same string in the test. Don't use g for yes/no checks, or create the regex inside the function.

3. Patterns that take forever

Nested quantifiers such as (a+)+ can make the engine try a huge number of ways to fail. Timings from the test machine, for a string of a's ending in !:

/^(a+)+$/ on 20 a's + "!"   48 ms
/^(a+)+$/ on 24 a's + "!"  109 ms
/^(a+)+$/ on 26 a's + "!"  420 ms
/^a+$/    on 26 a's + "!"  0.04 ms

Six more characters made it almost nine times slower, and the growth speeds up with every character, while the equivalent ^a+$ stayed under a millisecond. On a server, a pattern like this run on user input can be used to tie up the process (a ReDoS attack). Avoid a quantifier applied to a group that already has one, and limit input length before matching.

FAQ

What is the best regex for email?

A simple one such as ^[^\s@]+@[^\s@]+\.[^\s@]+$, used to catch typos, followed by a confirmation email. Patterns that try to follow the full address standard are long and still don't prove the mailbox exists.

Why does my regex work in the tester but not in my code?

Usually escaping. In a JavaScript string, "\d" loses its backslash; write "\\d" in new RegExp(), or use a regex literal /\d/. In Python, use raw strings: r"\d". The other common cause is a different engine; see the differences table.

What does \b mean?

A word boundary: the position between a word character and a non-word character. \bcat\b matches cat but not concatenate.

How do I match a literal dot or bracket?

Escape it with a backslash: \., \(, \[. Inside square brackets a dot is already literal: [.].

Is my text sent anywhere when I use the regex tester?

No. The tester runs in your browser.

Sources