Regular Expression#
Common Regex Patterns#
| Pattern | Description |
|---|---|
. | Any character except newline |
\d | Any digit [0-9] |
\D | Any non-digit |
\w | Any alphanumeric character and underscore [a-zA-Z0-9_] |
\W | Any non-alphanumeric character |
\s | Any whitespace (space, tab, newline) |
\S | Any non-whitespace |
\b | Word boundary (Position between \w and \W) |
+ | One or more |
* | Zero or more |
? | Zero or one (Optional) |
{n} | Exactly $n$ times |
{n,} | $n$ or more times |
{n,m} | Between $n$ and $m$ times |
Word Boundary \b#
\b is a zero-width assertion that matches the position where a word starts or ends. It doesn’t consume any characters.
eg. \bcat\b
- Matches: “cat”, “black cat”
- Does NOT match: “scatter”, “category”
Globbing vs Regular Expression#
| Feature | Globbing | Regular Expression |
|---|---|---|
| Zero or more characters | * | .* |
| Any single character | ? | . |
| Character set / Range | [abc], [a-z] | [abc], [a-z] |
| Negation (character set) | [!abc] or [^abc] | [^abc] |
| Alternation | {a,b} (Brace expansion) | (a|b) or [ab] |
| Quantifiers | N/A | +, ?, {n,m} |
| Anchors | Implicitly matches entire string | ^ (start), $ (end) |
| Escaping | \ | \ |
| Primary Use | Filename matching (Shell) | Text pattern matching (grep, sed) |
Capturing Groups#
Capturing groups allow you to isolate and extract specific parts of a match using parentheses ().
Example: Extracting Date Parts#
Pattern: (\d{4})-(\d{2})-(\d{2})
Input: 2026-06-16
- Group 0:
2026-06-16(The entire match) - Group 1:
2026(First parentheses) - Group 2:
06(Second parentheses) - Group 3:
16(Third parentheses)
Example: Backreferences#
Pattern: (\w+) \1
Input: hello hello
(\w+)matcheshelloand stores it in Group 1.\1refers back to Group 1, so it also matcheshello.- Result: Matches repeated words.