Linux Regular Expression

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Linux Regular Expression

Regular expression is also called regex or regexp. It is a very powerful tool in Linux. Regular expression is a pattern for a matching string that follows some pattern.

Regex can be used in a variety of programs like grep, sed, vi, bash, rename and many more.


Regular Expression Metacharacters

A regular expression may have one or several repeating metacharacters.

Metacharacter Description
. Replaces any character.
^ Matches start of string and represents characters not in the string.
$ Matches end of string.
* Matches zero or more times the preceding character.
  Represents the group of characters.
() Groups regular expressions.
? Matches exactly one character.
+ Matches one or more times the preceding character.
{N} Preceding character is matched exactly N times.
{N,} Preceding character is matched exactly N times or more.
{N,M} Preceding character is matched exactly N times, but not more than N times.
- Represents the range.
 Matches empty string at the edge of a word.
B Matches empty string if it is not at the edge of a word.
< Matches empty string at the beginning of a word.
> Matches empty string at the end of a word.

Regex Versions

There are three versions of regular expressions syntax:

  • BRE : Basic Regular Expressions
  • ERE : Extended Regular Expressions
  • PRCE: Perl Regular Expressions

Depending on tool or programs, one or more of these versions can be used.