๐Ÿ”ค Regular Expressions

โ† Back to Cheatsheets

A quick-reference for regex syntax. Regular expressions are patterns for matching and manipulating text. The core syntax is consistent across most tools โ€” Python's re, JavaScript's RegExp, grep -E, sed, and PCRE all share the same fundamentals, with minor differences in supported features.

Resources

regex101 โ€” Live tester with explanation regexr.com โ€” Visual reference Python re module MDN โ€” JS Regex regular-expressions.info

Basics

Most characters match themselves literally. A handful of characters โ€” . ^ $ * + ? { } [ ] \ | ( ) โ€” are special and must be escaped with \ to be treated as literals.

Quantifiers

Quantifiers apply to the preceding element (character, group, or class). By default they are greedy โ€” they match as much as possible. Append ? to make them lazy โ€” match as little as possible.

Character Classes

A character class matches one character from a defined set. Shorthands like \d are equivalent to their bracket form but more concise.

Anchors

Anchors are zero-width โ€” they match a position, not a character. They don't consume input.

Groups & Back-references

Parentheses group sub-expressions and capture their match for later use. Captured groups are numbered left-to-right by their opening parenthesis.

Lookahead & Lookbehind

Lookaround assertions are zero-width โ€” they check what's around the current position without consuming characters. Useful for adding conditions without including context in the match.

Flags / Modifiers

Flags change how the pattern is applied. In most languages they go after the closing delimiter: /pattern/flags.

Escaping

Any special character can be escaped with \ to match it literally. The full set of special characters: . ^ $ * + ? { } [ ] \ | ( )

Common Patterns

Ready-to-use patterns for common tasks. Test and adjust for your specific requirements โ€” general-purpose patterns always have edge cases.