The pattern language inside every text tool
Regex appears in grep, sed, awk, vim, your editor's find dialog, and every modern programming language. The dialects vary; the core grammar is stable.
Building blocks
- Any character:
. - Character class:
[abc]= a, b, or c.[^abc]= anything but.[a-z]= range. - Predefined:
\ddigit (PCRE),\wword,\swhitespace. - Anchors:
^start of line,$end.\bword boundary (PCRE).
Quantifiers
*— 0 or more.+— 1 or more (ERE/PCRE).?— 0 or 1 (ERE/PCRE).{3}— exactly 3.{2,5}— 2 to 5.
Grouping and alternation
(foo|bar)— foo or bar.(\d+)— capture digits, refer back as\1.
BRE vs ERE vs PCRE
- BRE (basic, default for grep/sed) —
+,?,{}, and()need backslashes. - ERE (extended,
grep -E,sed -E) — the modern, sane dialect. - PCRE (Perl-compatible,
grep -P) — full power: lookahead, lookbehind, named groups.
Practical patterns
- Email-ish:
[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,} - IP-ish:
\b(\d{1,3}\.){3}\d{1,3}\b - ISO date:
\d{4}-\d{2}-\d{2} - Trailing whitespace:
[[:space:]]+$
Real email validation is a nightmare; that pattern is just a strong filter. Don't try to write a perfect regex for human languages.