# Regular Expressions

The special characters (meta-characters) used for defining regular expressions are:

* . ^ $ + ? ( ) [ ] { } | \

# Character sets and character classes

OperatorsDescription
[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

OperatorsDescription
^Match the beginning of a line.
$Match the end of a line.

# Bracket Expressions

QuantifierCharacter Classes
[:alnum:]Alphanumeric characters.
[:alpha:]Alphabetic characters.
[:blank:]Space and tab.
[:digit:]Digits.
[:lower:]Lowercase letters.
[:upper:]Uppercase letters.

# Repetitions, Grouping, and References

OperatorsDescription
*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

ExpressionDescription
\bMatch the empty string at the edge of a word.
\BMatch 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.
\wMatch word constituent, it is a synonym for [_[:alnum:]] .
\WMatch non-word constituent, it is a synonym for [^_[:alnum:]] .
\sMatch whitespace, it is a synonym for [[:space:]] .
\SMatch non-whitespace, it is a synonym for [^[:space:]] .
\dMatch digit, it is a synonym for [[:dight:]] .
\DMatch 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.

.*?

Edited on