---
title: "RegEx"
description: "Regular expressions (regex or regexp) are patterns used to match character combinations in strings. They are powerful tools for pattern matching, validation, and text processing across many programming languages."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/regex
---

# RegEx

Regular expressions (regex or regexp) are powerful patterns used to match character combinations in strings. They enable sophisticated 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

Fundamental regex concepts and basic pattern matching techniques.

### Basic Syntax

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

**Keywords:** pattern, matching, flags, regex, test, match

#### Simple pattern matching

```regex
abc
```

_exec_
```javascript
pattern.test('abcdef')
```

_input_
```javascript
abcdef
```

_output_
```javascript
true
```

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

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

#### Case-insensitive matching

```regex
/hello/i
```

_exec_
```javascript
/hello/i.test('HELLO world')
```

_input_
```javascript
HELLO world
```

_output_
```javascript
true
```

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

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

#### Global matching

```regex
/a/g
```

_exec_
```javascript
'banana'.match(/a/g)
```

_input_
```javascript
banana
```

_output_
```javascript
['a', 'a', 'a']
```

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

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

**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.

### Character Classes

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

**Keywords:** character, class, bracket, range, negation, digits, letters

#### Matching character sets

```regex
[aeiou]
```

_exec_
```javascript
/[aeiou]/.test('hello')
```

_input_
```javascript
hello
```

_output_
```javascript
true
```

Matches any single vowel character from the set.

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

#### Character ranges

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

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

_input_
```javascript
abc
```

_output_
```javascript
true
```

Ranges match characters within specified inclusive boundaries.

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

#### Negated character class

```regex
[^0-9]
```

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

_input_
```javascript
abc7
```

_output_
```javascript
true
```

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

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

**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**: Ensure ^ is the first character [^...].

**Advanced notes:**

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

### Shorthand Classes

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

**Keywords:** shorthand, escape, digit, word, whitespace, dot

#### Digit matching with \d

```regex
\d+
```

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

_input_
```javascript
Price $25.99
```

_output_
```javascript
['25', '99']
```

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

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

#### Word character matching

```regex
\w+
```

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

_input_
```javascript
hello_world123
```

_output_
```javascript
['hello_world123']
```

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

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

#### Whitespace matching

```regex
\s+
```

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

_input_
```javascript
hello   world
```

_output_
```javascript
['hello', 'world']
```

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

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

**Best practices:**

- Use \d for digits instead of [0-9].
- Remember \D, \W, \S are negations.
- Combine with quantifiers for powerful patterns.

**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).

## 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.

**Keywords:** anchor, start, end, caret, dollar, begin, terminate

#### Start of string anchor

```regex
^hello
```

_exec_
```javascript
/^hello/.test('hello world')
```

_input_
```javascript
hello world
```

_output_
```javascript
true
```

^ anchors the pattern to the start of the string.

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

#### End of string anchor

```regex
world$
```

_exec_
```javascript
/world$/.test('hello world')
```

_input_
```javascript
hello world
```

_output_
```javascript
true
```

$ anchors the pattern to the end of the string.

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

#### Exact string matching

```regex
^hello world$
```

_exec_
```javascript
/^hello world$/.test('hello world')
```

_input_
```javascript
hello world
```

_output_
```javascript
true
```

Both ^ and $ ensure the entire string matches exactly.

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

**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.

### Word Boundaries

Detecting word boundaries with \b and \B.

**Keywords:** boundary, word, backslash-b, non-boundary, whitespace

#### Matching whole words only

```regex
\bword\b
```

_exec_
```javascript
/\bcat\b/.test('concatenate')
```

_input_
```javascript
concatenate
```

_output_
```javascript
false
```

\b ensures 'cat' is a whole word, not part of another word.

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

#### Word boundary matching

```regex
\bword\b
```

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

_input_
```javascript
the cat sat
```

_output_
```javascript
true
```

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

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

#### Non-word boundary

```regex
\Bword\B
```

_exec_
```javascript
/\Bcat\B/.test('concatenate')
```

_input_
```javascript
concatenate
```

_output_
```javascript
true
```

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

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

**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.

### Multiline Matching

Using the multiline flag to match across multiple lines.

**Keywords:** multiline, flag, newline, line, anchor, carriage

#### Single-line mode (default)

```regex
/^hello/
```

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

_input_
```javascript
foo
hello
```

_output_
```javascript
false
```

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

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

#### Multiline mode with flag

```regex
/^hello/m
```

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

_input_
```javascript
foo
hello
```

_output_
```javascript
true
```

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

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

#### Matching line patterns

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

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

_input_
```javascript
Info
Error: Failed
```

_output_
```javascript
true
```

Matches entire 'Error' line using multiline anchors.

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

**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**: Ensure 'm' flag is present 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.

## Quantifiers and Repetition

Specifying how many times elements should match.

### Quantifiers

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

**Keywords:** quantifier, repetition, asterisk, plus, question, braces, count

#### Zero or more matches

```regex
a*
```

_exec_
```javascript
/a*/.test('bbb')
```

_input_
```javascript
bbb
```

_output_
```javascript
true
```

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

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

#### One or more matches

```regex
a+
```

_exec_
```javascript
/a+/.test('aaa')
```

_input_
```javascript
aaa
```

_output_
```javascript
true
```

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

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

#### Exact quantity with braces

```regex
a{3}
```

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

_input_
```javascript
aaaaaa
```

_output_
```javascript
true
```

'{3}' matches exactly 3 occurrences.

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

**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).

### Greedy vs Lazy Matching

Understanding greedy and lazy (non-greedy) quantifiers.

**Keywords:** greedy, lazy, non-greedy, quantifier, backtrack, minimal

#### Greedy matching

```regex
a.*b
```

_exec_
```javascript
'axxxbxxxb'.match(/a.*b/)
```

_input_
```javascript
axxxbxxxb
```

_output_
```javascript
['axxxbxxxb']
```

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

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

#### Lazy matching

```regex
a.*?b
```

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

_input_
```javascript
axxxbxxxb
```

_output_
```javascript
['axxxb']
```

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

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

#### Lazy with + quantifier

```regex
a+?
```

_exec_
```javascript
'aaaa'.match(/a+?/)
```

_input_
```javascript
aaaa
```

_output_
```javascript
['a']
```

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

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

**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**: Ensure ? is 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.

### Alternation

Using | to match one pattern from multiple choices.

**Keywords:** alternation, pipe, choice, option, or, group

#### Simple alternation

```regex
cat|dog
```

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

_input_
```javascript
I have a cat
```

_output_
```javascript
true
```

| means OR - matches either 'cat' or 'dog'.

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

#### Multiple alternation options

```regex
red|green|blue
```

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

_input_
```javascript
the sky is blue
```

_output_
```javascript
true
```

Matches any of the three colors.

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

#### Alternation within groups

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

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

_input_
```javascript
Ms Smith
```

_output_
```javascript
true
```

Parentheses group alternatives; must match before 'Smith'.

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

**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.

## Groups and Capture

Using parentheses for grouping and capturing matched text.

### Capturing Groups

Using parentheses to capture and reference matched text.

**Keywords:** group, capture, parenthesis, reference, backreference, dollar

#### Basic capturing group

```regex
(\w+) (\w+)
```

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

_input_
```javascript
hello world
```

_output_
```javascript
['hello world', 'hello', 'world']
```

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

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

#### Backreference in pattern

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

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

_input_
```javascript
hello hello
```

_output_
```javascript
true
```

\1 refers back to what the first group captured.

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

#### Replace with capture groups

```regex
(\w+) (\w+)
```

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

_input_
```javascript
hello world
```

_output_
```javascript
world hello
```

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

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

**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 first ( - group 1 is 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.

### Non-Capturing Groups

Using parentheses for grouping without capturing.

**Keywords:** group, non-capturing, question, colon, cluster

#### Non-capturing group syntax

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

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

_input_
```javascript
I have a cat
```

_output_
```javascript
true
```

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

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

#### Non-capturing vs capturing

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

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

_input_
```javascript
foo baz
```

_output_
```javascript
['foo baz']
```

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

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

#### Complex non-capturing groups

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

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

_input_
```javascript
example.com
```

_output_
```javascript
true
```

Groups pattern without capturing each domain segment.

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

**Best practices:**

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

**Common errors:**

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

### Lookahead and Lookbehind

Using assertions to match patterns with conditional lookahead/lookbehind.

**Keywords:** lookahead, lookbehind, assertion, positive, negative, question

#### Positive lookahead

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

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

_input_
```javascript
user@example.com
```

_output_
```javascript
['user']
```

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

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

#### Negative lookahead

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

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

_input_
```javascript
example@
```

_output_
```javascript
['example']
```

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

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

#### Lookbehind assertion

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

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

_input_
```javascript
Price $50
```

_output_
```javascript
['50']
```

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

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

**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.

## Escaped Characters and Special Sequences

Escaping special characters and using special sequences.

### Escape Sequences

Using backslash to escape metacharacters and special characters.

**Keywords:** escape, backslash, metacharacter, literal, special, dot, asterisk

#### Escaping metacharacters

```regex
\. \* \+ \?
```

_exec_
```javascript
/\./.test('end.')
```

_input_
```javascript
end.
```

_output_
```javascript
true
```

Backslash escapes special characters so they match literally.

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

#### Escaping brackets and parentheses

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

_exec_
```javascript
/(test)/.test('(test)')
```

_input_
```javascript
(test)
```

_output_
```javascript
true
```

Escape brackets and parentheses to match them literally.

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

#### Escaping dollar and caret

```regex
\$ \^
```

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

_input_
```javascript
cost: $50
```

_output_
```javascript
true
```

Escape $ and ^ when you need literal matches.

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

**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.

### Character Escape

Escaping specific characters and special sequences like tabs and newlines.

**Keywords:** escape, tab, newline, carriage, form, feed, 

#### Tab and newline escapes

```regex
\t, \n, \r
```

_exec_
```javascript
/\t/.test('name\tvalue')
```

_input_
```javascript
name	value
```

_output_
```javascript
true
```

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

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

#### Matching whitespace patterns

```regex
\r\n
```

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

_input_
```javascript
line1
line2
```

_output_
```javascript
true
```

Matches Windows-style line endings (CRLF).

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

#### Null and other escapes

```regex
\0, \v, \f
```

_exec_
```javascript
/\0/.test('null\0char')
```

_input_
```javascript
null char
```

_output_
```javascript
true
```

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

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

**Best practices:**

- Use \n for cross-platform line matching.
- Combine escapes with other patterns intelligently.
- 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.

### Unicode and Special Sequences

Matching Unicode characters and special named sequences.

**Keywords:** unicode, escape, codepoint, hex, surrogate, special

#### Unicode hex escape

```regex
\uXXXX, \u0041
```

_exec_
```javascript
/\u0041/.test('ABC')
```

_input_
```javascript
ABC
```

_output_
```javascript
true
```

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

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

#### Unicode codepoint escape

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

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

_input_
```javascript
😀
```

_output_
```javascript
true
```

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

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

#### Unicode property escapes

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

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

_input_
```javascript
café
```

_output_
```javascript
true
```

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

- Requires 'u' flag.
- Very powerful for international text.

**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{...} is very powerful for Unicode categories.

## Practical Examples and Flags

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

### Common Patterns

Real-world regex patterns for validation and matching.

**Keywords:** pattern, email, url, phone, date, validation, example

#### Email validation pattern

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

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

_input_
```javascript
user@example.com
```

_output_
```javascript
true
```

Basic email pattern matching username@domain.extension.

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

#### URL matching pattern

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

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

_input_
```javascript
https://example.com
```

_output_
```javascript
true
```

Matches HTTP and HTTPS URLs with domain validation.

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

#### Phone number pattern (US format)

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

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

_input_
```javascript
(555) 123-4567
```

_output_
```javascript
true
```

Matches various US phone number formats.

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

**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.

### Regex Flags

Using flags to modify regex behavior globally.

**Keywords:** flag, global, case, insensitive, multiline, dotall, sticky

#### Global flag (g)

```regex
/pattern/g
```

_exec_
```javascript
'hello hello'.match(/hello/g)
```

_input_
```javascript
hello hello
```

_output_
```javascript
['hello', 'hello']
```

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

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

#### Case-insensitive flag (i)

```regex
/pattern/i
```

_exec_
```javascript
/HELLO/i.test('hello')
```

_input_
```javascript
hello
```

_output_
```javascript
true
```

The 'i' flag ignores case when matching.

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

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

```regex
/pattern/m, /pattern/s
```

_exec_
```javascript
/^test/m.test('\ntest')
```

_input_
```javascript
\ntest
```

_output_
```javascript
true
```

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

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

**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.

### String Operations with Regex

Using regex with JavaScript string methods.

**Keywords:** string, match, replace, split, search, test, exec

#### Test method

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

_exec_
```javascript
/hello/.test('hello world')
```

_input_
```javascript
hello world
```

_output_
```javascript
true
```

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

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

#### Match method

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

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

_input_
```javascript
hello world
```

_output_
```javascript
['hello', 'world']
```

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

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

#### Replace method

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

_exec_
```javascript
'hello world'.replace(/world/, 'universe')
```

_input_
```javascript
hello world
```

_output_
```javascript
hello universe
```

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

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

**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.
