Skip to main content

Regular Expressions

Regular expressions (regex) are patterns used to match character combinations in strings. They’re powerful tools for text processing, validation, and manipulation.

Basic Syntax

Common Flags

Basic Patterns

Exact String Match

Use the ^ and $ anchors to match the start and end of the string:

Match Empty String

Match Whitespace Sequences

Use the \s meta-sequence to match any whitespace character:

Match Line Breaks

Character Classes

Match Non-Word Characters

Match Alphanumeric, Dashes and Hyphens

Particularly useful when matching URL slugs:

Match Letters and Whitespaces

Advanced Patterns

Lookaheads

Pattern not included:

Text Inside Brackets

Validation Patterns

Email Validation

Phone Number Validation

URL Validation

Date Validation (DD/MM/YYYY)

Password Strength

Useful Methods

test()

Returns boolean:

match()

Returns array of matches:

matchAll()

Returns iterator of all matches with groups:

replace()

Replace matches:

replaceAll()

split()

Returns index of first match:

Capture Groups

Basic Groups

Named Groups

Non-Capturing Groups

Practical Examples

Extract All URLs

Chunk String into N-Size Chunks

Camel Case to Snake Case

Strip HTML Tags

Validate Hex Color

Performance Tips

Be careful with nested quantifiers like (a+)+ which can cause exponential time complexity. Use possessive quantifiers or atomic groups when possible.
Use (?:...) instead of (...) when you don’t need to capture the match. It’s slightly faster.
Use ^ and $ anchors when appropriate to avoid searching the entire string.
Store regex patterns in variables and reuse them instead of creating new ones each time.

Best Practices

Complex regex patterns are hard to read and maintain. Break them into smaller parts or use multiple simpler patterns.
Use the verbose flag in other languages or add comments in your code to explain what the pattern does.
Test regex patterns with various inputs, including edge cases, to ensure they work as expected.
For simple operations like checking if a string contains a substring, includes() is often clearer than regex.