Home › Developer Tools › Regex Cheat Sheet

Regex Cheat Sheet

A searchable library of tested regular expressions for everyday tasks, from validating emails and IP addresses to extracting hashtags and URLs. Every pattern has its own test box that highlights matches live, plus a quick syntax reference.

Last updated:

Validation patterns use the m flag so you can test one value per line; drop it to validate a single string. Matches are highlighted live as you edit the test text.

Regex syntax quick reference

TokenMeaningExample
Advertisement
Advertisement

How to use the Regex Cheat Sheet

  1. Search for what you need, such as email, date or ipv4, or pick a category tab.
  2. Read the description to see what the pattern accepts and where its limits are.
  3. Edit the test text on the card. Matches are highlighted as you type and the count updates; press Test to re-run.
  4. Copy the regex as a JavaScript literal or as the bare pattern for other languages.
  5. Check the syntax reference at the bottom when you want to adapt a pattern, then download the cheat sheet for offline use.

Regex flags explained

FlagNameEffectExample
gglobalFind all matches instead of stopping at the first"a1b2".match(/\d/g) → ["1", "2"]
iignore caseLetters match regardless of case/hello/i matches "HeLLo"
mmultiline^ and $ match at every line break/^\d+$/m checks each line
sdotAll. also matches line breaks/a.b/s matches "a\nb"
uunicodeTreats surrogate pairs as one character and enables \p{…}/\p{L}+/u matches "Zürich"
ystickyMatches only at lastIndex, useful for tokenizers/\d/y
dindicesAdds start and end positions of each group to the result/(a)/d.exec("ba").indices
vunicodeSetsUpgraded u mode with set operations in classes/[\p{L}--[a-z]]/v

Greedy vs lazy: a worked example

Given the text <b>bold</b> and <i>italic</i>:

  • /<.+>/ is greedy: .+ runs to the end of the string, then backtracks to the last >, so the single match is the whole text, 30 characters.
  • /<.+?>/g is lazy: .+? stops at the first >, giving four matches: <b>, </b>, <i>, </i>.
  • /<[^>]+>/g gives the same four matches without backtracking, because the negated class can never run past a >. Negated classes are usually the fastest and clearest choice.

Using these patterns in code

LanguageValidate a whole stringFind all matches
JavaScript/^\d{5}$/.test(zip)[...text.matchAll(/#\w+/g)]
Pythonre.fullmatch(r"\d{5}", zip)re.findall(r"#\w+", text)
PHPpreg_match('/^\d{5}$/', $zip)preg_match_all('/#\w+/', $text, $m)
Javazip.matches("\\d{5}")Pattern.compile("#\\w+").matcher(text)
C#Regex.IsMatch(zip, @"^\d{5}$")Regex.Matches(text, @"#\w+")
Goregexp.MustCompile(`^\d{5}$`).MatchString(zip)re.FindAllString(text, -1)

Tip: in languages where patterns are written as normal strings (Java, C++), every backslash must be doubled. Raw strings (r"…" in Python, @"…" in C#, backticks in Go) avoid that.

Frequently asked questions

Do these regex patterns work outside JavaScript?

Most do. The patterns use widely supported syntax that also works in Python, Java, C#, PHP (PCRE) and Go with small changes. Lookbehinds such as (?<!\w) are not supported in Go's RE2 engine, and \p{Extended_Pictographic} needs a Unicode-aware engine. Remove the slashes and flags when you use the bare pattern.

What is the best regex for email addresses?

There is no perfect one; the full RFC 5322 grammar is too complex for a practical regex. The pattern here accepts normal addresses and rejects obvious mistakes such as a missing @ or a domain without a dot. To be sure an address exists, send a confirmation email.

Why do the validation patterns use the m flag?

So that each line of the test box is checked as a separate value. With the m flag, ^ and $ match at the start and end of every line. When you validate one input field in your code, drop the m flag so the whole string must match.

Can a regex validate dates fully?

Only partly. The date patterns check the format and the ranges of months and days, but not month lengths or leap years, so 2026-02-30 still passes. Parse the date in code after the regex check.

What is catastrophic backtracking?

Some patterns with nested quantifiers, like (a+)+, can take exponential time on certain non-matching input, freezing a page or server (a ReDoS). The patterns on this page avoid ambiguous nesting, but always test custom patterns against long, nearly matching strings.

Is my test text sent anywhere?

No. All matching runs in your browser with the built-in JavaScript RegExp engine. Nothing you type is uploaded.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

Regex TesterTest and debug regular expressions live.URL ParserBreak a URL into its parts and edit query string parameters with a live rebuild.Email ValidatorCheck email lists and spot disposable addresses.JavaScript BeautifierFormat and beautify messy or minified JavaScript, or minify it.Bash Prompt GeneratorDrag and drop a custom PS1 prompt for bash or zsh with colors, git branch and a live preview.CSS Specificity CalculatorCalculate CSS selector specificity (a, b, c), including :is(), :not(), :has() and :where(), and compare.Math Formulas Cheat SheetSearchable algebra, geometry, trig, calculus and statistics formulas with a printable sheet.Online Python CompilerRun Python 3 in your browser with input(), numpy, pandas, charts and share links.JSON EditorEdit JSON in a tree and as code side by side: add, rename, drag, change types, undo and download.Unzip FilesOpen and extract ZIP files online.RAR & 7z ExtractorOpen RAR, 7z and other archives online and extract files.File Info ViewerCheck file size, type, date and MD5/SHA hashes.SQLite ViewerOpen .db and .sqlite files in your browser, browse tables and run SQL queries.DOCX ViewerOpen and read Word .docx files in your browser, then print or save them as HTML.EPUB ReaderOpen and read EPUB e-books in your browser with pages, a table of contents and font controls.What Is My BrowserSee your browser, version, OS, engine, screen and which web features it supports.Font ViewerPreview TTF, OTF, WOFF and WOFF2 fonts with sample text, waterfall, glyphs and metadata.Markdown EditorWrite Markdown with a toolbar, live split preview, autosave and .md or HTML export.JavaScript Keycode FinderPress any key to see its JavaScript key, code, keyCode, which, location and modifiers.QR Code ScannerScan QR codes with your camera or from an image and safely read the link or text.RAID CalculatorUsable capacity, efficiency and fault tolerance for RAID 0, 1, 5, 6, 10, 50 and 60 arrays.JSONPath TesterTest JSONPath expressions live: filters, slices, wildcards and recursive search, with matches highlighted.Mermaid Diagram EditorWrite Mermaid code and see flowcharts, sequence, Gantt and ER diagrams live. Export SVG or PNG.Country Codes ListSearch ISO 3166 alpha-2, alpha-3 and numeric country codes with calling codes and TLDs.CSS Selector TesterTest CSS selectors on your HTML: highlighted matches, match count and specificity.Git Cheat SheetSearchable Git command reference by task, with copy buttons and an undo/rename/fix wizard.HAR File ViewerOpen a .har file to see a waterfall timeline, headers, bodies, timings and size totals.jq PlaygroundRun jq filters on JSON in your browser with live output, flags and an example library.Markdown Cheat SheetInteractive Markdown syntax reference: edit every example and see the live rendered preview.Regex ExplainerPaste a regular expression and get a plain-English breakdown, railroad diagram and flag notes.XPath TesterTest XPath expressions on XML or HTML: highlighted matches, node paths, values and examples.EML File ViewerOpen .eml email files to read the message, headers and raw source and save attachments.Graphviz Online ViewerWrite Graphviz DOT code and render graphs live; switch layout engines, export SVG or PNG.JavaScript Online CompilerWrite and run JavaScript in your browser with a console, timing, error lines and share links.Jupyter Notebook ViewerOpen .ipynb files and read code, Markdown, math, tables, plots and errors without Python.LaTeX Table GeneratorEdit a table like a spreadsheet or paste from Excel and get LaTeX tabular or booktabs code.Log File ViewerOpen huge log files with level colors, regex and time filters, JSON pretty-print and tail -f.Logic Gate SimulatorBuild logic circuits with AND, OR, NOT, XOR gates and flip-flops; see live outputs and truth tables.Glob Pattern TesterTest glob patterns like **/*.js, {a,b} and !exclusions against a list of file paths.JMESPath TesterEvaluate JMESPath expressions against JSON live, the query language used by the AWS CLI.MongoDB Query TesterTest MongoDB find filters, projections and aggregation pipelines on sample JSON documents.Semantic Version CalculatorBump, compare, sort and test SemVer versions against npm ^, ~ and x ranges.XSLT TesterRun an XSLT 1.0 stylesheet on XML in your browser and see the output as HTML, XML or text.ASCII Diagram EditorDraw boxes, arrows and text on a character grid and copy plain-text diagrams for code and READMEs.DBF File ViewerOpen dBase .dbf files and shapefile tables, search and sort records, export CSV or XLSX.MBOX File ViewerOpen .mbox mail archives: list and search messages, read them, save attachments, export EML.MDB File ViewerOpen Access .mdb and .accdb databases in your browser: list tables, view rows, export CSV.Shapefile ViewerView zipped shapefiles on a map with the attribute table, then export to GeoJSON or CSV.MSG File ViewerOpen Outlook .msg emails in your browser: sender, recipients, body, headers and attachments.Online Code EditorVS Code-style editor in your browser: tabs, 50+ languages, find/replace, autosave.Online Hex EditorOpen any file as hex and ASCII, edit bytes, search, inspect values and save the result.PHP Online CompilerRun PHP 8 code in your browser with output, HTML preview, error lines and share links.PlantUML EditorWrite PlantUML and see sequence, class, activity and more diagrams live. Export SVG or PNG.Sorting Algorithm VisualizerWatch bubble, insertion, merge, quick, heap and radix sort step by step with live counters.Lottie ViewerOpen Lottie JSON or .lottie files to play, pause, scrub frames, change speed and see details.Diff ViewerPaste a git diff or .patch file and view it side by side or inline, with file navigation.EditorConfig GeneratorBuild an .editorconfig with indent, charset, line endings and trim rules per file pattern.Folder Compare ToolCompare two folders by file list, size and SHA-256 hash, then open a text diff of changed files.
See all 53 Code Playgrounds & Testers →