Toolypet
Back to Blog
Dev

Regular Expression Cheat Sheet: Collection of Commonly Used Patterns

A compilation of the most frequently used regex patterns and practical examples in web development.

Toolypet Team7 min read
Regular Expression Cheat Sheet: Collection of Commonly Used Patterns

Why Should You Learn Regular Expressions?

Regular expressions (Regex) are like a Swiss Army knife for developers. They seem difficult at first, but once you're familiar with them, you can replace dozens of lines of string processing code with just one line. Regular expressions shine in almost all string-related tasks: email validation, phone number extraction, log parsing, text replacement, and more.

The reason many developers fear regular expressions is that the syntax isn't immediately understandable. Code like /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ looks like a cipher. But once you understand the basic syntax, you can read this pattern logically too. In this article, we'll first explain the core syntax of regular expressions, then break down frequently used patterns in practice one by one.

Understanding Basic Syntax Systematically

Regular expression syntax can be broadly divided into four categories: metacharacters, quantifiers, groups, and anchors.

Metacharacters: Characters with Special Meaning

Metacharacters represent specific character sets or conditions.

SymbolMeaningExample
.Any character except newlinea.c -> abc, adc, a1c
\dDigit (0-9)\d+ -> 123, 4567
\DNon-digit character\D+ -> abc, !@#
\wWord character (a-z, A-Z, 0-9, _)\w+ -> hello_123
\WNon-word character\W -> space, special chars
\sWhitespace (space, tab, newline)\s+ -> multiple spaces
\SNon-whitespace character\S+ -> consecutive words

Quantifiers: Expressing Repetition

Quantifiers specify how many times the preceding element repeats.

SymbolMeaningExample
*0 or moreab* -> a, ab, abb, abbb
+1 or moreab+ -> ab, abb, abbb
?0 or 1colou?r -> color, colour
{n}Exactly n\d{4} -> 2025
{n,}n or more\d{2,} -> 10, 100, 1000
{n,m}Between n and m\d{2,4} -> 10, 100, 1000

Anchors and Boundaries

Anchors match positions, not characters themselves.

SymbolMeaningExample
^Start of string^Hello -> matches "Hello World"
$End of stringWorld$ -> matches "Hello World"
\bWord boundary\bcat\b -> matches "cat" only, not "catch"
\BNon-word boundary\Bcat -> cat in "catch"

Groups and Capture

Using parentheses allows you to group patterns and capture matched parts.

const dateStr = '2025-12-25';
const regex = /(\d{4})-(\d{2})-(\d{2})/;

const match = dateStr.match(regex);
console.log(match[0]); // '2025-12-25' (full match)
console.log(match[1]); // '2025' (first group - year)
console.log(match[2]); // '12'   (second group - month)
console.log(match[3]); // '25'   (third group - day)

Practical Pattern Collection: Breaking Down Each One

1. Email Validation

The email pattern is a classic regex example. Let's break it down step by step.

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

Pattern breakdown:

  • ^ - Start of string
  • [a-zA-Z0-9._%+-]+ - Local part (before @): 1 or more alphanumeric, dots, underscores, etc.
  • @ - @ symbol (literal)
  • [a-zA-Z0-9.-]+ - Domain name: 1 or more alphanumeric, dots, hyphens
  • \. - Dot (needs escaping)
  • [a-zA-Z]{2,} - Top-level domain: 2 or more alphabetic (com, org, museum, etc.)
  • $ - End of string

Edge case handling: This pattern validates most common emails but doesn't fully comply with RFC 5322 standard. For example, emails with quotes like "user name"@example.com won't match. In practice, format validation followed by actual email sending is the most reliable approach.

2. Password Strength Check

To validate complex password rules with regex, use lookahead.

// Minimum 8 chars, uppercase, lowercase, number, special character
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;

Pattern breakdown:

  • (?=.*[a-z]) - Must contain at least 1 lowercase (lookahead)
  • (?=.*[A-Z]) - Must contain at least 1 uppercase
  • (?=.*\d) - Must contain at least 1 digit
  • (?=.*[@$!%*?&]) - Must contain at least 1 special character
  • [A-Za-z\d@$!%*?&]{8,} - 8 or more allowed characters

Lookahead (?=...) checks if the pattern exists but doesn't consume characters. This allows checking multiple conditions simultaneously.

3. Phone Number Validation

A pattern to validate phone numbers.

const phoneRegex = /^(\+1)?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/;

Pattern breakdown:

  • (\+1)? - Optional country code
  • [-.\s]? - Optional separator (hyphen, dot, or space)
  • \(?\d{3}\)? - Area code, optionally wrapped in parentheses
  • \d{3} - First 3 digits
  • \d{4} - Last 4 digits
phoneRegex.test('123-456-7890');   // true
phoneRegex.test('(123) 456-7890'); // true
phoneRegex.test('+1 123 456 7890'); // true

4. Name Validation

When validating names, you can use character ranges for different languages.

// English names
const nameRegex = /^[a-zA-Z\s'-]{2,50}$/;

nameRegex.test('John Doe');    // true
nameRegex.test("O'Brien");     // true
nameRegex.test('Mary-Jane');   // true

5. URL Validation

URL patterns need to support various formats, making them complex.

const urlRegex = /^(https?:\/\/)?(www\.)?[\w-]+(\.[a-z]{2,})+([\/\w.-]*)*\/?$/i;

Pattern breakdown:

  • (https?:\/\/)? - Protocol (http:// or https://) optional
  • (www\.)? - www. optional
  • [\w-]+ - Domain name
  • (\.[a-z]{2,})+ - TLD like .com, .co.uk (1 or more)
  • ([\/\w.-]*)* - Path (optional)
  • \/?$ - Optional trailing slash
  • i flag - Case insensitive

6. IPv4 Address Validation

Each octet of an IPv4 address must be in the range 0-255. Expressing this in regex:

const ipv4Regex = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/;

Pattern breakdown (matching 0-255):

  • 25[0-5] - 250-255
  • 2[0-4]\d - 200-249
  • [01]?\d\d? - 0-199
ipv4Regex.test('192.168.1.1');     // true
ipv4Regex.test('256.1.1.1');       // false (256 out of range)
ipv4Regex.test('192.168.001.001'); // true (leading zeros allowed)

Performance Optimization

The biggest cause of slow regex is backtracking. Excessive use of greedy quantifiers can cause drastic performance degradation.

Greedy vs Lazy Quantifiers

// Greedy - matches as much as possible
'<div>content</div><div>more</div>'.match(/<div>.*<\/div>/);
// Result: '<div>content</div><div>more</div>' (entire string)

// Lazy - matches minimum needed
'<div>content</div><div>more</div>'.match(/<div>.*?<\/div>/);
// Result: '<div>content</div>' (first only)

Adding ? after a quantifier makes it lazy: *?, +?, ??

Optimization Tips

  1. Use anchors: Clearly limit scope with ^ and $
  2. Use specific character classes: Use [^<]* instead of .*
  3. Use non-capturing groups: Use (?:...) when capture isn't needed
// Capturing group - slower (stores match results)
/(abc)+/

// Non-capturing group - faster (doesn't store)
/(?:abc)+/

Differences by Language

FeatureJavaScriptPythonJava
Syntax/pattern/flagsr'pattern'Pattern.compile("pattern")
Unicode/u flagBuilt-in supportPattern.UNICODE_CASE
Named groups(?<name>...)(?P<name>...)(?<name>...)
LookaheadSupportedSupportedSupported
LookbehindVariable length limitedSupportedSupported

Using Regular Expressions in JavaScript

const str = 'Contact us at support@example.com or sales@example.com';
const regex = /[\w.-]+@[\w.-]+\.\w+/g;

// Find all matches
const emails = str.match(regex);
// ['support@example.com', 'sales@example.com']

// Replace
const masked = str.replace(regex, '[email hidden]');
// 'Contact us at [email hidden] or [email hidden]'

// Split
'a,b;c:d'.split(/[,;:]/);
// ['a', 'b', 'c', 'd']

// Iterative matching (matchAll)
for (const match of str.matchAll(/(\w+)@(\w+\.\w+)/g)) {
  console.log(`Local: ${match[1]}, Domain: ${match[2]}`);
}

Toolypet Regex Tester

The hardest part of writing regular expressions is getting immediate feedback. Toolypet's Regex Tester solves this problem:

  • Enter pattern and test string to see real-time matching results
  • Visually displays what each capture group matched
  • Easily test multiple flags (g, i, m) with toggles
  • Provides frequently used pattern templates

When debugging complex regular expressions, validating in Toolypet first is much more efficient than testing directly in code.

RegexRegular ExpressionValidationPattern Matching