gizmobench
BrowseDaily
← All guides

GizmoBench guides

Regex Cheat Sheet: Syntax, Examples and Testing

GizmoBench ·

A regular expression (regex) is a compact pattern that describes text: which characters, in what order, how many times, and where. Most of what you will ever write uses about twenty symbols, and they fit on one page. This cheat sheet lists those symbols, shows them in worked examples, explains how regex differs from the wildcards you use in file names, and ends with a testing routine. You can try every pattern here in our regex tester, which runs in your browser, needs no account and does its matching locally, so the text you paste stays on your device.

GizmoBench
Test Regex Patterns in Your Browser
Try patterns against sample text with GizmoBench’s browser-based regex tester, with no account or software installation required.
Visit

TL;DR

  • Learn the core set first: ., ^, $, *, +, ?, {n,m}, [...], \d, \w, \s, ( ), | and the backslash escape. Everything else builds on these.
  • Quantifiers are greedy by default (they match as much as possible); adding ? makes them lazy, and a negated class such as [^<>] is often the safer choice.
  • Regex is not one language. Named groups, lookbehind and shorthand classes differ between JavaScript, Python, Go and others, so test in the flavor you will run.
  • Regex matches text content; wildcards (globs) match file names. The * means different things in each.
  • Build a pattern in small pieces and test it against both text that should match and text that should not.

Table of Contents

The core symbols at a glance

The table below follows the metacharacters documented in the Python regular expression HOWTO and the MDN quantifiers reference. The two agree on this core, which is why it is the part worth memorizing.

Symbol Meaning Example Matches
. Any one character except a line break c.t cat, cut, c7t
^ Start of the string (or of each line in multiline mode) ^Hello Hello at the start
$ End of the string (or of each line in multiline mode) end$ end at the finish
* Zero or more of the previous item ab* a, ab, abbb
+ One or more of the previous item ab+ ab, abbb
? Zero or one of the previous item colou?r color, colour
{n} Exactly n times \d{4} 2026
{n,m} Between n and m times \d{2,4} 12, 123, 2026
[abc] One character from the list [aeiou] any lowercase vowel
[^abc] One character not in the list [^0-9] any non-digit
[a-z] One character in a range [A-Za-z] one ASCII letter
\d \w \s Digit, word character, whitespace \s+ one or more spaces or tabs
( ) Capture group (\d+)-(\d+) two numbers, each captured
(?: ) Group without capturing (?:ab)+ ab, abab
| Alternation (or) cat|dog cat or dog
\ Escape a metacharacter \. a literal dot

The Python documentation lists the full set of special characters as . ^ $ * + ? { } [ ] \ | ( ). If you want to match any of those literally, put a backslash in front.

Character classes: matching one of several characters

Square brackets define a set, and the pattern matches exactly one character from it. Per the Python HOWTO, you can list characters ([abc]) or use a range ([a-c]), and a leading ^ negates the set, so [^5] matches anything except the digit 5. Most metacharacters lose their special meaning inside brackets, so [.] matches a literal dot.

Two cautions save time:

  • [a-z] is not “any letter”. It covers the ASCII lowercase range only, so accented letters such as é fall outside it, as the iTechGuides cheat sheet points out.
  • Shorthands depend on the flavor. \d, \w and \s are convenient, but the exact characters they cover differ between engines. In Python, for example, \w on a string pattern matches Unicode letters unless you pass the re.ASCII flag.

POSIX tools such as grep and sed also offer named classes written inside brackets, like [[:upper:]] or [[:digit:]]. The Open Group specification defines these, including [:blank:], [:punct:] and [:xdigit:], and says they are recognized according to the current locale.

Quantifiers: how many times

A quantifier applies to the single item just before it: a character, a class or a group. The Python HOWTO notes that {0,}, {1,} and {0,1} are the long forms of *, + and ?, and that {m} means exactly m repetitions.

Greedy versus lazy

Quantifiers are greedy by default: they grab as much text as they can while still letting the whole pattern match. MDN gives a clean illustration: on the string some <foo> <bar> new </bar> </foo> thing, the greedy /<.*>/ matches from the first < all the way to the last >, while the lazy /<.*?>/ stops at the first > and returns just <foo>. Adding ? after a quantifier turns it lazy.

Greedy and lazy quantifier match boundaries

A lazy quantifier is not always the best fix. Jan Goyvaerts’ regular expressions quick start recommends <[^<>]+> for matching an HTML tag instead of a dot-based pattern, because the negated class cannot run past a closing bracket. The same guide advises using the dot sparingly, since it matches nearly everything.

Anchors and word boundaries: where a match happens

Anchors match a position, not a character. As Real Python puts it, they are zero-width: they consume nothing from the string but dictate where a match must occur.

  • ^ and $ mark the start and end of the input, or of each line when the multiline flag is on.
  • \b marks the boundary between a word character and a non-word character. \bcat\b matches “cat” as a whole word but not the cat inside “scatter” (an example from the iTechGuides cheat sheet). \B is its opposite.

One trap matters for validation. In Python, $ can match just before a trailing newline, so the ShellHacks guide to testing regex safely advises re.fullmatch or \Z when you need the whole string to match. If your pattern validates a field, check how your language treats that final newline.

Groups, alternation and escapes

Parentheses do two jobs. They group, so a quantifier can apply to a multi-character unit ((ab)+), and they capture, so you can reuse the matched piece. Per Omar Crosby’s cross-language regex guide, groups are numbered left to right by their opening parenthesis, and group 0 is the whole match. If you only need grouping, write (?:...) and the engine will not store a capture.

The pipe | means “or” and has the lowest precedence, so ^cat|dog$ means “starts with cat, or ends with dog”. Wrap the alternatives, as in ^(?:cat|dog)$, to anchor both.

The backslash removes special meaning from a symbol (\. is a literal dot) or introduces a shorthand (\d). There is a second layer to watch: the programming language parses string literals before the regex engine sees them. The iTechGuides cheat sheet notes that Python uses raw strings (r"\d+"), Java needs doubled backslashes ("\\d+"), and C# has verbatim strings. If a pattern works in a tester but fails in code, check this first. Our JSON escape tool is handy when the pattern has to live inside a JSON string, where quotes and backslashes need escaping again.

Groups, alternation and escapes

Worked examples

These patterns are illustrations to learn from, not production validators. Paste each into the tester with the sample text and watch which parts highlight.

1. Optional letters: color or colour

Pattern: colou?r. The ? makes the u optional, so it matches both spellings. This is the same example used in the Goyvaerts quick start.

2. A date in a fixed layout

Pattern: \b(\d{4})-(\d{2})-(\d{2})\b. Against Invoice dated 2026-11-22. it matches 2026-11-22 and captures year, month and day as groups 1, 2 and 3. It checks the shape only: it will also accept 2026-99-99, because regex counts digits, not calendar days.

3. Whole words only

Pattern: \bcat\b. In “The cat sat in the scatter pile” only the standalone word is matched.

4. Trim repeated whitespace

Pattern: \s{2,} replaced with a single space. This collapses runs of spaces, tabs and line breaks. Because \s includes newlines, use [ ]{2,} if you want to keep line breaks. Our regex replace page previews the result of a find-and-replace before you apply it, and the remove characters page does the same for cleaning text, such as stripping everything except letters and digits with [^A-Za-z0-9 ].

5. Rearranging with capture groups

Take names written as Lovelace, Ada and turn them into Ada Lovelace. Pattern: (\w+), (\w+). Replacement: $2 $1. The replacement refers back to the captures by number. In JavaScript you can also name them, as in (?<last>\w+), (?<first>\w+) with $<first> $<last>. The capture groups replace page covers both $1 and named forms.

Complex validation: don’t hand-roll it

Email addresses are the classic temptation. A Berkeley statistics department regex tutorial notes that a fully correct pattern for a format like RFC 822 email addresses is extremely complex, and that it is better to use a bug-vetted implementation than to write your own. It also advises building regexes in pieces and testing them on examples, which is the approach used in the testing routine below.

Regex versus wildcards

The two look alike, which causes real confusion. The Rocky Linux documentation draws the line this way: regular expressions match the content of files and are used by commands such as grep, sed and awk, while wildcards match file and directory names and are used with commands such as ls, cp, mv and find.

The symbol that trips people up is the star:

Wildcard (glob) Regex
Matches against File and directory names Text content
* means Any run of characters Zero or more of the previous item
? means Exactly one character Zero or one of the previous item (or lazy modifier)
Example *.txt lists text files dogs* matches dog and dogs

The dogs* result comes from Shawn Powers’ Linux Journal article on globbing and regex: in regex the star repeats the preceding character, and zero s characters still satisfies the pattern. The same article gives a practical habit: quote your grep patterns, because the shell may expand an unquoted * as a glob before grep ever sees it. His example is grep file* README.TXT, which can silently turn into a search for a matching file name in the current directory.

To express “anything” in regex, the equivalent of the glob * is .*.

Flavors: why a pattern works in one place and not another

“Regex” is a family of dialects. The core table above is portable, but advanced features are not. According to the iTechGuides flavor comparison and the Birdor regex cheatsheet:

Feature JavaScript Python re Go (RE2)
Named group syntax (?<name>...) (?P<name>...) both (?P<name>) and (?<name>)
Lookahead Yes Yes No
Lookbehind Depends on runtime Yes, with restrictions No
Backreferences Yes Yes No (numbered)

The underlying reason, described in the Crosby guide, is engine design. Linear-automaton engines such as Go, Rust and RE2 give up backreferences and lookaround, while backtracking engines support them but can suffer catastrophic backtracking on adversarial input. Possessive quantifiers and atomic groups can help there, though they exist in PCRE, Java and Python’s third-party regex module and not in standard Python re, JavaScript, Go or Rust.

The practical rule: write and test in the same flavor you will deploy. Our tester uses JavaScript matching, so it is the right place to build patterns for browser code, Node.js and any tool that uses JavaScript regex. For other engines, stick to the portable core when you can and confirm the rest in the target runtime.

A testing routine that catches most mistakes

The ShellHacks guide and the iTechGuides cheat sheet converge on a similar approach. Here it is as steps you can follow in a browser tab:

  1. Name your engine. Know the language, version and flags (case-insensitive, multiline, global) before you start.
  2. Collect examples. Write down several strings that must match and several that must not, including an empty string, a line break and a string with unusual characters.
  3. Build in pieces. Start with the simplest part, confirm it, then add one element at a time. If you do not want to start from a blank box, the regex generator builds a first pattern from examples you provide, which you can then refine.
  4. Read the highlights and the groups. Check that each capture contains what you expect and that numbering matches your plan.
  5. Test replacement separately. A pattern can match correctly and still produce the wrong output once you add $1-style references.
  6. Check the usual suspects. The ShellHacks list of common causes is missing anchors, greedy quantifiers, unescaped dots, forgotten flags and flavor mismatches such as using \d in grep -E.
  7. Try long, hostile input. Nested quantifiers like (a+)+ can take exponential time on a backtracking engine, so test a long string that almost matches before shipping.

If your input is large, local processing is a real advantage: the text never leaves your computer while you iterate.

Using the GizmoBench regex tools

Our regex tester shows JavaScript matches, groups and replacements as you type, and it runs entirely in your browser with no sign-up. Core tools on the site are free to use without an account. Related pages cover specific jobs: previewing a find and replace, cleaning text by removing characters and replacing with capture groups. If you are working with minified code, the JavaScript beautifier makes it readable before you search it, and the character counter is useful for checking length limits on the text you extract. Developer utilities such as the JSON Formatter and Base64 Encoder & Decoder sit together on the developer tools page.

FAQ

What is the difference between .* and .*?

Both match any run of characters, but .* is greedy and takes as much as it can, while .*? is lazy and takes as little as possible. On <a> <b>, <.*> matches the whole string and <.*?> matches only <a>. When a negated class like [^>]* fits your data, it is often more predictable than either.

Why does my regex work in one tool but not in my code?

Usually it is a flavor difference or string escaping. Named groups, lookbehind and shorthand classes vary between engines, and languages such as Java need doubled backslashes while Python prefers raw strings. Confirm the engine and flags first, then check how the pattern is written inside the string literal.

Is regex the same as a wildcard?

No. Wildcards (globs) match file and directory names and are expanded by the shell, while regex searches text content in tools such as grep, sed and awk. The star also behaves differently: in a glob it matches any characters, and in regex it repeats the previous item.

Should I write my own email validation regex?

A short pattern can check the rough shape of an address, such as text, an at sign and a domain, but a pattern that follows the full email standard is extremely complex. For anything critical, use a well-tested library instead and keep the regex simple.

Sources