---
title: "RegEx"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/regex
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# RegEx

Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They handle pattern matching, validation, and text processing across many programming languages.

6 Categories18 Sections54 ExamplesPublished: 01 Apr 2023Updated: 27 Feb 2025

RegExRegular ExpressionsPattern MatchingText ProcessingValidationSyntaxAnchorsCharacter Classes

[Markdown for AI(opens in a new tab)](/regex/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Config & Data Formats](/series/config--data-formats)1/5

[NextYAML](/cheatsheets/yaml)

All posts in this series (5)

Cheatsheets5

1.  [RegExYou are here](/cheatsheets/regex)
2.  [YAML](/cheatsheets/yaml)
3.  [JSON](/cheatsheets/json)
4.  [Markdown](/cheatsheets/markdown)
5.  [TOML](/cheatsheets/toml)

Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They handle pattern matching, validation, and text processing across nearly all programming languages.

Browse the sections below to explore regex syntax, patterns, and practical examples.

[Getting Started](#category-getting-started)

-   [Basic Syntax](#section-basic-syntax)
-   [Character Classes](#section-character-classes)
-   [Shorthand Classes](#section-shorthand-classes)

[Anchors and Boundaries](#category-anchors-boundaries)

-   [Anchors](#section-anchors)
-   [Word Boundaries](#section-word-boundaries)
-   [Multiline Matching](#section-multiline-matching)

[Quantifiers and Repetition](#category-quantifiers-repetition)

-   [Quantifiers](#section-quantifiers)
-   [Greedy vs Lazy Matching](#section-greedy-vs-lazy)
-   [Alternation](#section-alternation)

[Groups and Capture](#category-groups-capture)

-   [Capturing Groups](#section-capturing-groups)
-   [Non-Capturing Groups](#section-non-capturing-groups)
-   [Lookahead and Lookbehind](#section-lookahead-lookbehind)

[Escaped Characters and Special Sequences](#category-escaped-characters)

-   [Escape Sequences](#section-escape-sequences)
-   [Character Escape](#section-character-escape)
-   [Unicode and Special Sequences](#section-unicode-and-special)

[Practical Examples and Flags](#category-practical-patterns)

-   [Common Patterns](#section-common-patterns)
-   [Regex Flags](#section-regex-flags)
-   [String Operations with Regex](#section-string-operations)

No commands found

Try adjusting your search term

## Getting Started

Fundamental regex concepts and basic pattern matching techniques.

### Basic Syntax

Introduction to regex pattern matching, flags, and basic syntax.

#### Accessibility

Ensure regex patterns and examples are clear and labeled.

#### Best Practices

-   Start with simple patterns before complex ones.
-   Use flags appropriately (i, g, m, s).
-   Test patterns thoroughly before using in production.

#### Common Errors

-   **Pattern not matching expected strings:** Check for case sensitivity and special characters.
-   **Finding only first match when all needed:** Add the 'g' flag to match globally.

#### Keywords

patternmatchingflagsregextestmatch

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions)

#### Simple pattern matching

Tests if the string contains the literal pattern 'abc'.

Code

```
1abc
```

Execution

```
1pattern.test('abcdef')
```

Input

```
1abcdef
```

Output

```
1true
```

-   Simple patterns match literal characters in order.
-   The test() method returns true if pattern is found.

#### Case-insensitive matching

The 'i' flag makes the pattern case-insensitive.

Code

```
1/hello/i
```

Execution

```
1/hello/i.test('HELLO world')
```

Input

```
1HELLO world
```

Output

```
1true
```

-   The 'i' flag ignores case when matching.
-   Useful for user input validation.

#### Global matching

The 'g' flag finds all matches, not just the first one.

Code

```
1/a/g
```

Execution

```
1'banana'.match(/a/g)
```

Input

```
1banana
```

Output

```
1['a', 'a', 'a']
```

-   Without 'g', only the first match is returned.
-   'g' is essential for global replacements.

### Character Classes

Matching sets of characters using brackets, ranges, and negation.

#### Accessibility

Clearly label what each character class matches.

#### Best Practices

-   Use ranges \[a-z\] instead of listing all characters.
-   Combine multiple ranges \[a-zA-Z0-9\].
-   Use negation \[^...\] for exclusion patterns.

#### Common Errors

-   **Hyphen causing unexpected ranges:** Escape it or place it at the end \[a-z-\].
-   **Negation not working:** Put ^ first in the class \[^...\].

#### Advanced Notes

-   **Complex Classes:** Combine multiple ranges like \[a-zA-Z0-9\_-\] for flexible matching.
-   **Metacharacters in Classes:** Most metacharacters lose special meaning inside \[\].

#### Keywords

characterclassbracketrangenegationdigitsletters

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes)

#### Matching character sets

Matches any single vowel character from the set.

Code

```
1[aeiou]
```

Execution

```
1/[aeiou]/.test('hello')
```

Input

```
1hello
```

Output

```
1true
```

-   \[abc\] matches any one character from the set.
-   Characters are evaluated individually.

#### Character ranges

Ranges match characters within specified inclusive boundaries.

Code

```
1[a-z], [A-Z], [0-9], [a-zA-Z0-9]
```

Execution

```
1/[a-z]+/.test('abc')
```

Input

```
1abc
```

Output

```
1true
```

-   \[a-z\] matches lowercase letters.
-   \[0-9\] matches numeric digits.

#### Negated character class

The '^' at the start means NOT, matching any non-digit character.

Code

```
1[^0-9]
```

Execution

```
1/[^0-9]/.test('abc7')
```

Input

```
1abc7
```

Output

```
1true
```

-   \[^abc\] matches any character except a, b, or c.
-   ^ must be the first character in the class.

### Shorthand Classes

Using shorthand character class escapes like \\d, \\w, \\s for common patterns.

#### Accessibility

Explain what each shorthand matches clearly.

#### Best Practices

-   Use \\d for digits instead of \[0-9\].
-   Remember \\D, \\W, \\S are negations.
-   Combine with quantifiers to match longer sequences.

#### Common Errors

-   **Not escaping backslash in strings:** Use raw strings or double backslashes '\\\\d' not '\\d'.
-   **Confusing \\w with only letters:** Remember \\w includes digits and underscores.

#### Advanced Notes

-   **Dot Metacharacter:** '.' matches any character except newline (unless /s flag).
-   **Negation Pairs:** Each shorthand has a negated version (\\D, \\W, \\S).

#### Keywords

shorthandescapedigitwordwhitespacedot

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes)

#### Digit matching with \\d

\\d matches any digit, + means one or more. Extracts all numbers.

Code

```
1\d+
```

Execution

```
1'Price: $25.99'.match(/\d+/g)
```

Input

```
1Price $25.99
```

Output

```
1['25', '99']
```

-   \\d is equivalent to \[0-9\].
-   \\D matches non-digits.

#### Word character matching

\\w matches word characters (letters, digits, underscores).

Code

```
1\w+
```

Execution

```
1'hello_world123'.match(/\w+/g)
```

Input

```
1hello_world123
```

Output

```
1['hello_world123']
```

-   \\w matches \[a-zA-Z0-9\_\].
-   \\W matches non-word characters.

#### Whitespace matching

\\s matches any whitespace character (space, tab, newline).

Code

```
1\s+
```

Execution

```
1'hello   world'.split(/\s+/)
```

Input

```
1hello   world
```

Output

```
1['hello', 'world']
```

-   \\s is equivalent to \[ \\t\\n\\r\\f\\v\].
-   \\S matches non-whitespace.

## Anchors and Boundaries

Using anchors to match positions in strings and word boundaries.

### Anchors

Using ^ and $ to match start and end of strings or lines.

#### Accessibility

Clearly identify what start and end positions mean.

#### Best Practices

-   Use ^ and $ for strict full-string validation.
-   Combine with other patterns for targeted matching.
-   Remember anchors don't consume characters.

#### Common Errors

-   **Anchor matching wrong position:** Check the multiline (m) flag affects anchors.
-   **Pattern after $ or before ^:** Anchors should be at the beginning/end of the pattern.

#### Advanced Notes

-   **Word Anchors:** Use \\A for absolute start and \\Z for absolute end.
-   **Multiline Mode:** The 'm' flag makes ^ and $ match line breaks.

#### Keywords

anchorstartendcaretdollarbeginterminate

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions)

#### Start of string anchor

^ anchors the pattern to the start of the string.

Code

```
1^hello
```

Execution

```
1/^hello/.test('hello world')
```

Input

```
1hello world
```

Output

```
1true
```

-   ^ must be at the beginning to anchor to string start.
-   Only matches if 'hello' is at position 0.

#### End of string anchor

$ anchors the pattern to the end of the string.

Code

```
1world$
```

Execution

```
1/world$/.test('hello world')
```

Input

```
1hello world
```

Output

```
1true
```

-   Only matches if 'world' is at the very end.
-   Useful for validating complete strings.

#### Exact string matching

Together, ^ and $ require the entire string to match exactly.

Code

```
1^hello world$
```

Execution

```
1/^hello world$/.test('hello world')
```

Input

```
1hello world
```

Output

```
1true
```

-   Useful for strict validation.
-   The string must be exactly 'hello world'.

### Word Boundaries

Detecting word boundaries with \\b and \\B.

#### Accessibility

Explain what constitutes a word boundary clearly.

#### Best Practices

-   Use \\b for whole word matching in search operations.
-   Combine with ^ and $ for complete string validation.
-   Remember \\b works with punctuation boundaries too.

#### Common Errors

-   **Partial word matching when full word needed:** Add \\b at both sides \\bword\\b.
-   **Not finding words before punctuation:** \\b handles punctuation correctly.

#### Keywords

boundarywordbackslash-bnon-boundarywhitespace

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions)

#### Matching whole words only

\\b requires 'cat' to be a whole word, not part of another word.

Code

```
1\bword\b
```

Execution

```
1/\bcat\b/.test('concatenate')
```

Input

```
1concatenate
```

Output

```
1false
```

-   \\b matches between a word and non-word character.
-   Prevents partial matches within larger words.

#### Word boundary matching

Matches 'cat' only when it's a standalone word.

Code

```
1\bword\b
```

Execution

```
1/\bcat\b/.test('the cat sat')
```

Input

```
1the cat sat
```

Output

```
1true
```

-   Works with word boundaries around punctuation too.
-   Useful for word-based search and replace.

#### Non-word boundary

\\B matches when NOT at a word boundary (inside a word).

Code

```
1\Bword\B
```

Execution

```
1/\Bcat\B/.test('concatenate')
```

Input

```
1concatenate
```

Output

```
1true
```

-   \\B is the opposite of \\b.
-   Useful for finding patterns within words.

### Multiline Matching

Using the multiline flag to match across multiple lines.

#### Accessibility

Explain line breaks and multiline behavior clearly.

#### Best Practices

-   Use 'm' flag when processing multiline text.
-   Combine ^ and $ for line-specific matching.
-   Remember without 'm', ^ and $ only affect whole string.

#### Common Errors

-   **Pattern not matching lines:** Add the 'm' flag for multiline behavior.
-   **Forgetting newlines in test strings:** Use \\n explicitly in test strings.

#### Advanced Notes

-   **Dotall Flag:** The 's' flag makes . match newlines too.
-   **Line Ending Styles:** Be aware of \\r\\n (Windows) vs \\n (Unix) newlines.

#### Keywords

multilineflagnewlinelineanchorcarriage

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions)

#### Single-line mode (default)

Without m flag, ^ only matches start of entire string.

Code

```
1/^hello/
```

Execution

```
1/^hello/.test('foo\nhello')
```

Input

```
1foo2hello
```

Output

```
1false
```

-   'hello' on second line doesn''t match ^hello without m flag.'

#### Multiline mode with flag

With m flag, ^ matches after newlines too, not just string start.

Code

```
1/^hello/m
```

Execution

```
1/^hello/m.test('foo\nhello')
```

Input

```
1foo2hello
```

Output

```
1true
```

-   The 'm' flag makes ^ and $ line-aware.
-   Useful for multiline text processing.

#### Matching line patterns

Matches entire 'Error' line using multiline anchors.

Code

```
1/^Error:.*/m
```

Execution

```
1/^Error:.*/m.test('Info\nError: Failed')
```

Input

```
1Info2Error: Failed
```

Output

```
1true
```

-   Combine m flag with ^ and $ for line-based patterns.

## Quantifiers and Repetition

Specifying how many times elements should match.

### Quantifiers

Using \*, +, ?, and {n,m} to specify repetition counts.

#### Accessibility

Clearly label what each quantifier means.

#### Best Practices

-   Use + for at least one match, \* for optional matching.
-   Use {n,m} for specific range requirements.
-   Be careful with \* and empty matches.

#### Common Errors

-   **Matching when shouldn't with \*:** Remember \* includes zero occurrences.
-   **Range syntax incorrect:** Use {n,m} not {n-m} for ranges.

#### Advanced Notes

-   **Possessive quantifiers:** Use ++ or \*+ or +? to prevent backtracking.
-   **Greedy behavior:** By default quantifiers are greedy (match maximum).

#### Keywords

quantifierrepetitionasteriskplusquestionbracescount

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers)

#### Zero or more matches

'\*' matches zero or more occurrences. Even no 'a' matches.

Code

```
1a*
```

Execution

```
1/a*/.test('bbb')
```

Input

```
1bbb
```

Output

```
1true
```

-   a\* matches '', 'a', 'aa', 'aaa', etc.
-   Always matches because \* includes 0 occurrences.

#### One or more matches

'+' matches one or more occurrences. At least one required.

Code

```
1a+
```

Execution

```
1/a+/.test('aaa')
```

Input

```
1aaa
```

Output

```
1true
```

-   a+ requires at least one 'a'.
-   a+ doesn't match empty string.

#### Exact quantity with braces

'{3}' matches exactly 3 occurrences.

Code

```
1a{3}
```

Execution

```
1/a{3}/.test('aaaaaa')
```

Input

```
1aaaaaa
```

Output

```
1true
```

-   a{3} matches exactly 'aaa'.
-   a{1,3} matches 1 to 3 occurrences.

### Greedy vs Lazy Matching

Understanding greedy and lazy (non-greedy) quantifiers.

#### Accessibility

Explain difference between greedy and lazy matching clearly.

#### Best Practices

-   Use greedy by default for simplicity.
-   Use lazy when you need minimal matching.
-   Be aware of performance implications.

#### Common Errors

-   **Matching too much with .\*:** Use .\*? for lazy matching.
-   **Lazy matching not working:** Put ? immediately after the quantifier.

#### Advanced Notes

-   **Backtracking:** Greedy quantifiers backtrack when needed; lazy quantifiers don't.
-   **Performance:** Lazy quantifiers can be faster for specific patterns.

#### Keywords

greedylazynon-greedyquantifierbacktrackminimal

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers)

#### Greedy matching

Greedy .\* matches as much as possible, stopping at last 'b'.

Code

```
1a.*b
```

Execution

```
1'axxxbxxxb'.match(/a.*b/)
```

Input

```
1axxxbxxxb
```

Output

```
1['axxxbxxxb']
```

-   .\* is greedy; it matches from first 'a' to last 'b'.
-   Quantifiers are greedy by default.

#### Lazy matching

Lazy .\*? matches as little as possible, stopping at first 'b'.

Code

```
1a.*?b
```

Execution

```
1'axxxbxxxb'.match(/a.*?b/)
```

Input

```
1axxxbxxxb
```

Output

```
1['axxxb']
```

-   .\*? is lazy; it matches from first 'a' to first 'b'.
-   Add ? after any quantifier to make it lazy.

#### Lazy with + quantifier

a+? matches minimally, just one 'a' instead of all.

Code

```
1a+?
```

Execution

```
1'aaaa'.match(/a+?/)
```

Input

```
1aaaa
```

Output

```
1['a']
```

-   Adding ? makes any quantifier lazy.
-   Lazy quantifiers match minimum instead of maximum.

### Alternation

Using | to match one pattern from multiple choices.

#### Accessibility

Clearly explain the OR logic in alternation.

#### Best Practices

-   Group alternatives with () when needed.
-   Order options from most specific to less specific.
-   Consider performance when using many alternatives.

#### Common Errors

-   **Alternation applying to wrong part:** Use parentheses to group (cat|dog) Smith.
-   **Too many alternatives causing slowness:** Use character classes \[abc\] instead when possible.

#### Advanced Notes

-   **Atomic Groups:** Use (?>...) to prevent backtracking in alternation.
-   **Performance:** Fewer alternatives and specific patterns are faster.

#### Keywords

alternationpipechoiceoptionorgroup

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Disjunctions)

#### Simple alternation

| means OR, matching either 'cat' or 'dog'.

Code

```
1cat|dog
```

Execution

```
1/cat|dog/.test('I have a cat')
```

Input

```
1I have a cat
```

Output

```
1true
```

-   cat|dog matches 'cat' or 'dog'.
-   Leftmost match wins if multiple alternatives match.

#### Multiple alternation options

Matches any of the three colors.

Code

```
1red|green|blue
```

Execution

```
1/red|green|blue/.test('the sky is blue')
```

Input

```
1the sky is blue
```

Output

```
1true
```

-   Use | to separate multiple alternatives.
-   Order matters; first matching option is used.

#### Alternation within groups

Parentheses group alternatives; must match before 'Smith'.

Code

```
1(Mr|Ms|Mrs) Smith
```

Execution

```
1/^(Mr|Ms|Mrs) Smith$/.test('Ms Smith')
```

Input

```
1Ms Smith
```

Output

```
1true
```

-   (cat|dog) applies alternation to grouped part only.
-   Without (), cat|dog box matches 'cat' or 'dog box'.

## Groups and Capture

Using parentheses for grouping and capturing matched text.

### Capturing Groups

Using parentheses to capture and reference matched text.

#### Accessibility

Explain how groups capture and reference text clearly.

#### Best Practices

-   Use capturing groups to extract data.
-   Reference groups with $n in replacements.
-   Use \\n inside the pattern for backreferences.

#### Common Errors

-   **Backreference number incorrect:** Count groups from the first (; group 1 is the first (.
-   **Replacement not working:** Use $1, $2 in replacement string (not \\1).

#### Advanced Notes

-   **Named Groups:** Use (?<name>...) for named captures.
-   **Multiple Groups:** Supports up to 9 backreferences without named groups.

#### Keywords

groupcaptureparenthesisreferencebackreferencedollar

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences)

#### Basic capturing group

Parentheses create capture groups. Result includes full match and each group.

Code

```
1(\w+) (\w+)
```

Execution

```
1'hello world'.match(/(\w+) (\w+)/)
```

Input

```
1hello world
```

Output

```
1['hello world', 'hello', 'world']
```

-   Group 1 captures 'hello', Group 2 captures 'world'.
-   Array includes full match at index 0.

#### Backreference in pattern

\\1 refers back to what the first group captured.

Code

```
1(\w+) \1
```

Execution

```
1/(\w+) \1/.test('hello hello')
```

Input

```
1hello hello
```

Output

```
1true
```

-   \\1 references the first group.
-   Useful for matching repeated patterns.

#### Replace with capture groups

$1, $2, etc. reference captured groups in replacement.

Code

```
1(\w+) (\w+)
```

Execution

```
1'hello world'.replace(/(\w+) (\w+)/, '$2 $1')
```

Input

```
1hello world
```

Output

```
1world hello
```

-   $0 is the full match.
-   Useful for rearranging captured text.

### Non-Capturing Groups

Using parentheses for grouping without capturing.

#### Accessibility

Explain differences between capturing and non-capturing groups.

#### Best Practices

-   Use (?:...) when you don't need to capture.
-   This improves performance slightly.
-   Makes regex less cluttered with unnecessary captures.

#### Common Errors

-   **Forgetting the ? in (?::** Use (?:...) not (...) for non-capturing.
-   **Trying to reference non-capturing group:** Non-capturing groups can't be referenced with \\1.

#### Keywords

groupnon-capturingquestioncoloncluster

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Backreferences)

#### Non-capturing group syntax

(?:...) groups without capturing the match.

Code

```
1(?:cat|dog)
```

Execution

```
1/(?:cat|dog)/.test('I have a cat')
```

Input

```
1I have a cat
```

Output

```
1true
```

-   (?:...) works like (...) but doesn't capture.
-   Useful when you only need grouping, not extraction.

#### Non-capturing vs capturing

Non-capturing groups don't create extra array entries.

Code

```
1(?:foo|bar) baz vs (foo|bar) baz
```

Execution

```
1'foo baz'.match(/(?:foo|bar) baz/)
```

Input

```
1foo baz
```

Output

```
1['foo baz']
```

-   Capturing group would create index \[1\].
-   Non-capturing is slightly more efficient.

#### Complex non-capturing groups

Groups pattern without capturing each domain segment.

Code

```
1\b(?:\w+\.)+com\b
```

Execution

```
1/\b(?:\w+\.)+com\b/.test('example.com')
```

Input

```
1example.com
```

Output

```
1true
```

-   Useful for repeated grouping patterns.
-   Makes regex cleaner when captures not needed.

### Lookahead and Lookbehind

Using assertions to match patterns with conditional lookahead/lookbehind.

#### Accessibility

Clearly explain how assertions work without consuming characters.

#### Best Practices

-   Use lookahead/lookbehind for conditional matching.
-   Remember they don't consume characters.
-   Helpful for extracting specific parts without delimiters.

#### Common Errors

-   **Including lookahead in the match result:** Remember lookahead/lookbehind don't consume.
-   **Lookbehind not supported in some languages:** JavaScript supports both since ES2018.

#### Advanced Notes

-   **Lookbehind Support:** Older JavaScript versions don't support lookbehind.
-   **Nesting:** Lookahead and lookbehind can be nested.

#### Keywords

lookaheadlookbehindassertionpositivenegativequestion

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions)

#### Positive lookahead

(?=...) matches only if followed by the pattern, but doesn't consume it.

Code

```
1\w+(?=@)
```

Execution

```
1'user@example.com'.match(/\w+(?=@)/)
```

Input

```
1user@example.com
```

Output

```
1['user']
```

-   Matches 'user' only if followed by @.
-   The @ is not included in the match.

#### Negative lookahead

(?!...) matches only if NOT followed by the pattern.

Code

```
1\w+(?!@)
```

Execution

```
1/'example@'.match(/\w+(?!@)/)
```

Input

```
1example@
```

Output

```
1['example']
```

-   Matches word chars not followed by @.
-   Useful for exclusion patterns.

#### Lookbehind assertion

(?<=...) matches only if preceded by the pattern.

Code

```
1(?<=\$)\d+
```

Execution

```
1"/'Price: \$50'.match(/(?<=\\$)\\d+/)"
```

Input

```
1Price $50
```

Output

```
1['50']
```

-   Matches digits only if preceded by $.
-   The $ is not included in the match.

## Escaped Characters and Special Sequences

Escaping special characters and using special sequences.

### Escape Sequences

Using backslash to escape metacharacters and special characters.

#### Accessibility

Clearly show which characters need escaping and why.

#### Best Practices

-   Escape any special regex character when matching literally.
-   Use regex escape helpers in your language if available.
-   Be careful with string escaping too (\\\\d vs \\d).

#### Common Errors

-   **Escaping in string vs regex:** Remember both string and regex need escaping.
-   **Forgetting to escape special chars:** If it's a regex special char, escape it.

#### Advanced Notes

-   **Double Escaping:** Strings and regex both escape; 'string' uses \\, regex uses \\.
-   **Raw Strings:** Some languages have raw strings to avoid double escaping.

#### Keywords

escapebackslashmetacharacterliteralspecialdotasterisk

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes)

#### Escaping metacharacters

Backslash escapes special characters so they match literally.

Code

```
1\. \* \+ \?
```

Execution

```
1/\./.test('end.')
```

Input

```
1end.
```

Output

```
1true
```

-   \\. matches literal dot, not any character.
-   Most regex metacharacters need escaping.

#### Escaping brackets and parentheses

Escape brackets and parentheses to match them literally.

Code

```
1\( \) \[ \] \{ \}
```

Execution

```
1/(test)/.test('(test)')
```

Input

```
1(test)
```

Output

```
1true
```

-   \\( matches literal ( not a group.
-   All bracket types need escaping.

#### Escaping dollar and caret

Escape $ and ^ when you need literal matches.

Code

```
1\$ \^
```

Execution

```
1/\$/.test('cost: $50')
```

Input

```
1cost: $50
```

Output

```
1true
```

-   \\$ matches literal $.
-   \\^ matches literal ^.

### Character Escape

Escaping specific characters and special sequences like tabs and newlines.

#### Accessibility

Explain what each character escape represents clearly.

#### Best Practices

-   Use \\n for cross-platform line matching.
-   Combine escapes with other patterns as needed.
-   Test with actual newlines in data.

#### Common Errors

-   **Platform-specific line ending issues:** Use \\n or match both \\r\\n and \\n.
-   **Whitespace not matching as expected:** Remember \\s matches more than just these escapes.

#### Keywords

escapetabnewlinecarriageformfeed

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes)

#### Tab and newline escapes

\\t matches tab, \\n matches newline, \\r matches carriage return.

Code

```
1\t, \n, \r
```

Execution

```
1/\t/.test('name\tvalue')
```

Input

```
1name  value
```

Output

```
1true
```

-   These are whitespace character escapes.
-   Useful for parsing structured data.

#### Matching whitespace patterns

Matches Windows-style line endings (CRLF).

Code

```
1\r\n
```

Execution

```
1/\r\n/.test('line1\r\nline2')
```

Input

```
1line12line2
```

Output

```
1true
```

-   \\r\\n is Windows line ending.
-   \\n is Unix line ending.

#### Null and other escapes

Special escapes for null, vertical tab, and form feed.

Code

```
1\0, \v, \f
```

Execution

```
1/\0/.test('null\0char')
```

Input

```
1nullchar
```

Output

```
1true
```

-   \\0 matches null character.
-   \\v is vertical tab, \\f is form feed.

### Unicode and Special Sequences

Matching Unicode characters and special named sequences.

#### Accessibility

Explain Unicode notation and usage clearly.

#### Best Practices

-   Use \\u{...} with 'u' flag for modern Unicode support.
-   Remember 'u' flag is essential for surrogates.
-   Test with actual Unicode content.

#### Common Errors

-   **Unicode not matching without u flag:** Add 'u' flag: /pattern/u.
-   **Emoji not matching correctly:** Use \\u{...} with 'u' flag for emoji.

#### Advanced Notes

-   **Surrogate Pairs:** UTF-16 uses surrogates; 'u' flag handles this automatically.
-   **Property Escapes:** \\p{...} matches whole Unicode categories.

#### Keywords

unicodeescapecodepointhexsurrogatespecial

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes)

#### Unicode hex escape

\\u0041 represents Unicode character 'A' (U+0041).

Code

```
1\uXXXX, \u0041
```

Execution

```
1/\u0041/.test('ABC')
```

Input

```
1ABC
```

Output

```
1true
```

-   Unicode escapes use 4 hex digits.
-   Useful for matching international characters.

#### Unicode codepoint escape

\\u{...} with u flag matches Unicode by codepoint with variable length.

Code

```
1\u{XXXXX}, \u{1F600}
```

Execution

```
1/\u{1F600}/.test('😀')
```

Input

```
1😀
```

Output

```
1true
```

-   Requires 'u' flag for proper surrogate pair handling.
-   Supports emoji and beyond-BMP characters.

#### Unicode property escapes

\\p{...} matches Unicode character properties with 'u' flag.

Code

```
1\p{Letter}, \P{Number}
```

Execution

```
1/\p{Letter}/u.test('café')
```

Input

```
1café
```

Output

```
1true
```

-   Requires 'u' flag.
-   Useful for international text.

## Practical Examples and Flags

Common real-world patterns, flags, and string operations.

### Common Patterns

Real-world regex patterns for validation and matching.

#### Accessibility

Provide clear examples of what each pattern matches.

#### Best Practices

-   Use existing validation libraries when possible.
-   Test patterns with expected and unexpected inputs.
-   Document complex patterns for future maintainers.

#### Common Errors

-   **Overly strict patterns rejecting valid input:** Make patterns flexible to common variations.
-   **Overly loose patterns accepting invalid input:** Use anchors and character classes carefully.

#### Advanced Notes

-   **Internationalization:** Email and phone patterns vary by country.
-   **Library Usage:** Consider using validation libraries instead of regex.

#### Keywords

patternemailurlphonedatevalidationexample

[Learn more](https://www.regular-expressions.info/)

#### Email validation pattern

Basic email pattern matching username@domain.extension.

Code

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

Execution

```
1/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test('user@example.com')
```

Input

```
1user@example.com
```

Output

```
1true
```

-   This is simplified; RFC 5322 is more complex.
-   Works for most common email formats.

#### URL matching pattern

Matches HTTP and HTTPS URLs with domain validation.

Code

```
1^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$
```

Execution

```
1/^https?:/.test('https://example.com')
```

Input

```
1https://example.com
```

Output

```
1true
```

-   Simplified example; full URL regex is quite complex.
-   Use URL parsing libraries for production.

#### Phone number pattern (US format)

Matches various US phone number formats.

Code

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

Execution

```
1/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test('(555) 123-4567')
```

Input

```
1(555) 123-4567
```

Output

```
1true
```

-   Handles parentheses, dashes, dots, and spaces.
-   Captures area code, exchange, and line number.

### Regex Flags

Using flags to modify regex behavior globally.

#### Accessibility

Clearly explain what each flag does.

#### Best Practices

-   Combine flags as needed (/pattern/gi for global case-insensitive).
-   Document why each flag is used in your regex.
-   Remember flags affect the entire pattern.

#### Common Errors

-   **Expecting all matches without 'g' flag:** Add 'g' flag for global matching.
-   **Flag position incorrect:** Flags come after the closing /, not inside.

#### Advanced Notes

-   **Unicode Flag:** The 'u' flag enables proper Unicode support.
-   **Sticky Flag:** The 'y' flag matches starting from lastIndex.

#### Keywords

flagglobalcaseinsensitivemultilinedotallsticky

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags)

#### Global flag (g)

The 'g' flag finds all matches, not just the first.

Code

```
1/pattern/g
```

Execution

```
1'hello hello'.match(/hello/g)
```

Input

```
1hello hello
```

Output

```
1['hello', 'hello']
```

-   Without 'g', only first match is returned.
-   Essential for replace-all operations.

#### Case-insensitive flag (i)

The 'i' flag ignores case when matching.

Code

```
1/pattern/i
```

Execution

```
1/HELLO/i.test('hello')
```

Input

```
1hello
```

Output

```
1true
```

-   Useful for case-insensitive searches.
-   Affects both pattern and input.

#### Multiline and Dotall flags (m, s)

'm' makes ^ and $ match lines. 's' makes . match newlines.

Code

```
1/pattern/m, /pattern/s
```

Execution

```
1/^test/m.test('\ntest')
```

Input

```
1\ntest
```

Output

```
1true
```

-   'm' flag processes multiline text.
-   's' flag makes . match including newlines.

### String Operations with Regex

Using regex with JavaScript string methods.

#### Accessibility

Provide clear examples of string method usage.

#### Best Practices

-   Use test() for boolean checks.
-   Use match() to extract data.
-   Use split() to parse structured strings.
-   Use replace() for transformations.

#### Common Errors

-   **replace() only replacing first match:** Add 'g' flag: /pattern/g.
-   **Forgetting to use the result:** Remember strings are immutable; assign result to variable.

#### Advanced Notes

-   **Callback Functions:** replace() supports callback for complex replacements.
-   **Split with Regex:** split() uses regex for sophisticated string parsing.

#### Keywords

stringmatchreplacesplitsearchtestexec

[Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match)

#### Test method

test() returns true if pattern matches, false otherwise.

Code

```
1/pattern/.test(string)
```

Execution

```
1/hello/.test('hello world')
```

Input

```
1hello world
```

Output

```
1true
```

-   Returns boolean only.
-   Fastest method for simple matching.

#### Match method

match() returns array of all matches with 'g' flag.

Code

```
1string.match(/pattern/g)
```

Execution

```
1'hello world'.match(/\w+/g)
```

Input

```
1hello world
```

Output

```
1['hello', 'world']
```

-   Returns null if no match found.
-   Without 'g', returns match with capture groups.

#### Replace method

replace() replaces first match. Use 'g' flag for all matches.

Code

```
1string.replace(/pattern/g, 'replacement')
```

Execution

```
1'hello world'.replace(/world/, 'universe')
```

Input

```
1hello world
```

Output

```
1hello universe
```

-   Can use $1, $2 for capture group references.
-   Can be used with callback functions.

Was this useful?

## Tags

#RegEx#Regular Expressions#Pattern Matching#Text Processing#Validation#Syntax#Anchors#Character Classes

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=RegEx&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex&title=RegEx&summary=Regular%20expressions%20\(regex%20or%20regexp\)%20are%20patterns%20used%20to%20match%20character%20combinations%20in%20strings.%20They%20handle%20pattern%20matching%2C%20validation%2C%20and%20text%20processing%20across%20many%20programming%20languages.&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=RegEx%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex&text=RegEx "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex&title=RegEx "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex&t=RegEx "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex&media=&description=Regular%20expressions%20\(regex%20or%20regexp\)%20are%20patterns%20used%20to%20match%20character%20combinations%20in%20strings.%20They%20handle%20pattern%20matching%2C%20validation%2C%20and%20text%20processing%20across%20many%20programming%20languages. "Share on Pinterest")[Email](<mailto:?subject=RegEx&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fregex>)

## Comments

## You might also enjoy

More posts on similar topics

## [YAML](/cheatsheets/yaml)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   YAML
-   Configuration
-   Data Serialization
-   DevOps
-   Infrastructure

YAML (YAML Ain't Markup Language) is a human-friendly data serialization language widely used for configuration files, data exchange, and infrastructure-as-code. It emphasizes readability and uses ind

#YAML#Configuration#Data Serialization+6 tags

[read more](/cheatsheets/yaml)

## [JSON](/cheatsheets/json)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   JSON
-   Data Serialization
-   Web API
-   Configuration

JSON (JavaScript Object Notation) is a lightweight, text-based data exchange format. It's universally supported across programming languages and provides a simple, readable way to structure and transm

#JSON#Data Format#Data Serialization+5 tags

[read more](/cheatsheets/json)

## [Markdown](/cheatsheets/markdown)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Markup Language
-   Markdown
-   Documentation
-   Formatting
-   Content Creation
-   Writing

Markdown is a lightweight markup language for writing formatted content with a simple, readable syntax. It was created for writing on the web, and is now used in documentation, blogs, and note-taking

#Markdown#Formatting#Text+6 tags

[read more](/cheatsheets/markdown)

## [TOML](/cheatsheets/toml)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Data Format
-   TOML
-   Configuration
-   Data Serialization
-   Settings

TOML (Tom's Obvious, Minimal Language) is a human-friendly configuration file format. Designed to be minimal, readable, and unambiguous, it's used extensively in package manifests (like Cargo.toml and

#TOML#Configuration#Data Format+5 tags

[read more](/cheatsheets/toml)

## [Grep](/cheatsheets/grep)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

Best practices for grep usageAlways quote patterns to prevent shell interpretation of special characters Use -E flag for complex patterns to avoid escaping issues with basic regex

#Grep#Search#Pattern Matching+3 tags

[read more](/cheatsheets/grep)

## [Sed](/cheatsheets/sed)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

This sed reference covers basic text substitution through advanced scripting techniques, with practical examples for text processing, file editing, and automation.

#Sed#Stream Editor#Text Transformation+3 tags

[read more](/cheatsheets/sed)

6 related posts
