January 18, 2024 8 min read

Regex Cheat Sheet: Complete Regular Expression Guide

Master regular expressions with this comprehensive cheat sheet and practical examples.

Regular expressions (regex) are powerful tools for pattern matching in strings. While they can seem intimidating at first, once you understand the basics, they become invaluable for text processing, validation, and data extraction.

Basic Syntax

PatternDescriptionExample
.Any character except newlinea.c matches "abc", "a1c"
^Start of string^Hello matches "Hello world"
$End of stringworld$ matches "Hello world"
\dAny digit (0-9)\d+ matches "123"
\wWord character (a-z, A-Z, 0-9, _)\w+ matches "hello_123"
\sWhitespace (space, tab, newline)\s+ matches spaces

Quantifiers

PatternDescriptionExample
*0 or moreab*c matches "ac", "abc", "abbc"
+1 or moreab+c matches "abc", "abbc"
?0 or 1colou?r matches "color", "colour"
{n}Exactly n times\d{3} matches "123"
{n,}n or more times\d{2,} matches "12", "123"
{n,m}Between n and m times\d{2,4} matches "12", "1234"

Character Classes

PatternDescriptionExample
[abc]Any of a, b, or c[aeiou] matches vowels
[^abc]Not a, b, or c[^0-9] matches non-digits
[a-z]Range: a to z[A-Za-z] matches letters
\DNon-digit\D+ matches "abc"
\WNon-word character\W matches "@", "#"
\SNon-whitespace\S+ matches words

Groups and Lookahead

PatternDescription
(abc)Capturing group
(?:abc)Non-capturing group
(?=abc)Positive lookahead
(?!abc)Negative lookahead
(?<=abc)Positive lookbehind
(?<!abc)Negative lookbehind

Common Regex Patterns

Email Validation

^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

URL Validation

^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$

Phone Number (US)

^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

Password (Strong)

^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

IPv4 Address

^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

Hex Color Code

^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$

Test Your Regex Patterns

Try out these patterns with our free online regex tester.

Try Regex Tester →

Regex Tips

  • Start simple: Build your regex piece by piece
  • Use non-greedy quantifiers: Add ? after * or + for minimal matching
  • Escape special characters: Use \ before . * + ? ^ $ { } [ ] \ | ( )
  • Test incrementally: Test parts of your regex as you build it
  • Use comments: In verbose mode, add # comments for clarity

Conclusion

Regular expressions are a powerful tool every developer should know. Bookmark this cheat sheet and practice with our Regex Tester to master pattern matching.