Regular Expressions Cheat Sheet

What Are Regular Expressions?

Regular expressions (regex or regexp) are patterns used to match, search, and manipulate text. They are one of the most powerful tools in a developer’s toolkit, supported in virtually every programming language, text editor, and command-line tool. A well-crafted regex can replace dozens of lines of string-parsing code with a single expression.

Despite their power, regular expressions have a reputation for being difficult to read and write. This guide breaks down the syntax into manageable pieces and provides practical patterns you can use immediately.

Basic Character Matching

The simplest regex patterns match literal characters:

Character classes let you match one character from a set:

Predefined character classes provide shortcuts:

Quantifiers

Quantifiers specify how many times a pattern should repeat:

By default, quantifiers are greedy, meaning they match as much text as possible. Adding ? after a quantifier makes it lazy, matching as little as possible:

This distinction matters when extracting content between delimiters. For example, given the text <b>one</b><b>two</b>, the pattern <b>.*</b> greedily matches the entire string, while <b>.*?</b> matches <b>one</b> only.

Anchors and Boundaries

Anchors match positions rather than characters:

These are essential for precise matching. \bcat\b matches “cat” as a whole word but not “category” or “concatenate.” Without word boundaries, you would get false matches in longer words.

Groups and Alternation

Groups use parentheses to create sub-patterns:

Captured groups can be referenced later:

Common Practical Patterns

Here are regex patterns for everyday tasks:

Note that simple regex patterns for emails and URLs work for common cases but do not cover every edge case defined in the respective RFCs. For production validation, consider using dedicated libraries.

Lookaheads and Lookbehinds

Lookahead and lookbehind assertions match a position based on what comes before or after, without including that text in the match:

These are useful for extracting text adjacent to specific patterns without capturing the delimiter.

Regex Flags

Flags modify how the pattern is applied:

Tips for Writing Better Regex

Follow these practices to write maintainable patterns:

Try our free Regex Tester — no signup required.

Explore all free tools on CalcHub

Browse Tools