Regex Quick Reference
Luke Hebert
- 2 minutes read - 305 wordsRegex patterns can feel like a foreign language until you build a small, reliable set of go-to snippets. The patterns below cover the most common tasks I reach for in shell scripts and log analysis: extracting email addresses, using lookarounds, and matching specific character classes. Keep this page handy as a quick reference while you work.
Find Email Addresses
A reliable one-liner for pulling email addresses out of a log file:
egrep -o '[A-Za-z0-9.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}' email.log | sort | uniqThe -o flag prints only the matched portion, and piping through sort | uniq removes duplicates.
Forward and Backward Lookups
Perl-compatible lookarounds let you match text based on what surrounds it without consuming that surrounding text:
grep -oP '(?<=<)\S*(?=>:)'This example extracts the content between < and >: without including the delimiters themselves.
Special Meta Characters
| Pattern | Meaning |
|---|---|
^ | Line starts with |
$ | Line ends with |
Meta Characters
| Pattern | Meaning |
|---|---|
[] | Character class (single characters) |
. | Matches any character except newline |
() | Grouping (full expressions) |
| | Or (alternation) |
Qualifiers
| Pattern | Meaning |
|---|---|
? | Optional match (zero or one) |
+ | One or more of the preceding element |
* | Any number including zero of the preceding element |
{2,5} | Specify length (2 to 5 characters) |
Perl Look Ahead and Behind (grep -P)
These require the -P flag to enable Perl-compatible regex:
| Pattern | Meaning |
|---|---|
(?=blah) | Positive look ahead |
(?<=blah) | Positive look behind |
(?:blah) | Non-capture group |
.*? | Lazy match instead of greedy |
Character Shorthand Classes
| Pattern | Meaning | Equivalent |
|---|---|---|
\d | A digit | [0-9] |
\D | A non-digit | [^0-9] |
\w | A word character | [a-zA-Z0-9_] |
\W | A non-word character | [^a-zA-Z0-9_] |
\s | A whitespace character | [ \t\n\r\f] |
\S | A non-whitespace character | [^ \t\n\r\f] |
When in doubt, test your pattern against a small sample file first. The grep -oP combination is the fastest way to iterate on a pattern before committing it to a script.