Regular Expressions (Regex)
Regex are patterns for matching text. Used with grep, sed, awk, and many programs.
Basic characters
| Pattern | Matches |
|---|---|
. | Any single character |
* | Zero or more of previous |
+ | One or more of previous |
? | Zero or one of previous |
^ | Start of line |
$ | End of line |
\b | Word boundary |
\d | Digit (in PCRE) |
\w | Word character |
\s | Whitespace |
Character classes
[abc] # a, b, or c
[^abc] # Not a, b, or c
[a-z] # Lowercase letter
[A-Z] # Uppercase letter
[0-9] # Digit
[a-zA-Z0-9] # Alphanumeric
Quantifiers
a{3} # Exactly 3 a's: aaa
a{2,5} # 2 to 5 a's
a{2,} # 2 or more a's
Groups and alternation
(cat|dog) # cat or dog
(abc)+ # One or more 'abc'
With grep
grep 'pattern' file # Basic regex
grep -E 'pattern' file # Extended regex
grep -P 'pattern' file # Perl-compatible regex
grep '^[A-Z]' file # Lines starting with uppercase
grep '[0-9]\{3\}-[0-9]\{4\}' file # Phone numbers
grep -E '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' emails.txt
Practical examples
# Find IP addresses
grep -E '\b[0-9]{1,3}(\.[0-9]{1,3}){3}\b' file.txt
# Find email addresses
grep -E '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]+' file.txt
# Lines with exactly 5 characters
grep -E '^.{5}$' file.txt