Skip to main content

Common Regex Patterns

(Note: All examples below assume you are using grep -E for Extended Regular Expressions).

1. Line Anchors (^ and $)

Anchors do not match text; they match positions in the line.

  • ^ (Caret): Matches the beginning of the line.
  • $ (Dollar): Matches the end of the line.

Examples:

# Find lines that START with "ERROR"
grep -E "^ERROR" app.log

# Find lines that END with "failed"
grep -E "failed$" app.log

# Find completely empty lines
grep -E "^$" app.log

2. Character Classes ([])

Brackets allow you to define a set of characters. Any single character from that set will trigger a match.

# Matches "cat", "bat", or "rat"
grep -E "[cbr]at" file.txt

# Ranges: Matches any lowercase letter followed by a digit
grep -E "[a-z][0-9]" file.txt

# Inversion (^ inside brackets): Matches any character EXCEPT a vowel
grep -E "[^aeiou]" file.txt

POSIX Bracket Expressions

Because standard grep -E does not support \d for digits or \w for words, you should use POSIX classes to ensure your scripts run on all UNIX variants (macOS, Alpine, Linux).

POSIX ClassMatchesPCRE Equivalent
[[:alnum:]]Alphanumeric (A-Z, a-z, 0-9)N/A
[[:alpha:]]Letters (A-Z, a-z)N/A
[[:digit:]]Digits (0-9)\d
[[:space:]]Whitespace (space, tab, newline)\s
[[:punct:]]PunctuationN/A

Example:

# Portable way to find a 4-digit number
grep -E "[[:digit:]]{4}" file.txt

3. Quantifiers (?, *, +, {})

Quantifiers dictate how many times the preceding character (or group) must appear.

  • ?: Zero or one time (Optional).
  • *: Zero or more times.
  • +: One or more times.
  • {n,m}: Between n and m times.

Examples:

# Matches "color" or "colour" (the 'u' is optional)
grep -E "colou?r" text.md

# Matches "go", "goo", "gooo", etc. (must have at least one 'o')
grep -E "go+" text.md

# Matches exactly 3 digits
grep -E "[0-9]{3}" text.md

4. The Wildcard Dot (.)

The dot matches any single character (except a newline). It is frequently combined with the * quantifier (.*) to represent "any text of any length," similar to how a glob * works in the shell.

# Matches "error" followed by ANY amount of text, followed by "failed"
# e.g., "error: user auth token has failed"
grep -E "error.*failed" app.log