Regular Expressions
Regular Expressions
The special characters (meta-characters) used for defining regular expressions are:
* . ^ $ + ? ( ) [ ] { } | \
Character sets and character classes
| Operators | Description |
|---|---|
[abc] |
Match any single character from from the listed characters |
[a-z] |
Match any single character from the range of characters |
[^abc] |
Match any single character not among listed characters |
[^a-z] |
Match any single character not among listed range of characters |
. |
Match any single character except a newline (\n) |
\ |
Turn off (escape) the special meaning of a metacharacter |
Location-specific matches
| Operators | Description |
|---|---|
^ |
Match the beginning of a line. |
$ |
Match the end of a line. |
Bracket Expressions
| Quantifier | Character Classes |
|---|---|
[:alnum:] |
Alphanumeric characters. |
[:alpha:] |
Alphabetic characters. |
[:blank:] |
Space and tab. |
[:digit:] |
Digits. |
[:lower:] |
Lowercase letters. |
[:upper:] |
Uppercase letters. |
Repetitions, Grouping, and References
| Operators | Description |
|---|---|
* |
Match zero or more instances of the preceding character or regex. |
? |
Match zero or one instance of the preceding character or regex. |
+ |
Match one or more instances of the preceding character or regex. |
{n,m} |
Match a range of occurrences (at least n, no more than m) of preceding character of regex. |
| |
Match the character or expression to the left or right of the vertical bar. |
Here are some examples of repetitions:
[[:digit:]]*: any number of digits (zero or more)[[:digit:]]+: at least one digit[[:digit:]]?: zero or one digits[[:digit:]]{1,3}: at least one and no more than three digits[[:digit:]]{2,}: two or more digits
Special Backslash Expressions
| Expression | Description |
|---|---|
\b |
Match the empty string at the edge of a word. |
\B |
Match the empty string provided it’s not at the edge of a word. |
\< |
Match the empty string at the beginning of a word. |
\> |
Match the empty string at the end of a word. |
\w |
Match word constituent, it is a synonym for [_[:alnum:]]. |
\W |
Match non-word constituent, it is a synonym for [^_[:alnum:]]. |
\s |
Match whitespace, it is a synonym for [[:space:]]. |
\S |
Match non-whitespace, it is a synonym for [^[:space:]]. |
\d |
Match digit, it is a synonym for [[:dight:]]. |
\D |
Match non-digit, it is a synonym for [^[:dight:]]. |
Greedy matching
Regular expression pattern matching is greedy—by default, the longest matching string is chosen.
.*
To get a non-greedy match, you can use the modifier ? after the quantifier. However, this requires that we use the Perl syntax. In order for grep to use the Perl syntax, we need to use the -P option.
.*?
All articles on this blog are licensed under CC BY-NC-SA 4.0 unless otherwise stated.