Skip to main content
In this lesson, we’ll dive into extended regular expressions (ERE) on Linux, compare them with basic regex (BRE), and demonstrate how to leverage powerful metacharacters—without drowning in backslashes. You’ll learn to match repetitions, optional elements, alternation, ranges, sub-expressions, and negations using grep, egrep, sed, and other tools.

Why Extended Regular Expressions?

Basic regular expressions require backslashes to enable special operators (\+, \?, \|). EREs simplify syntax and unlock built-in support for:
  • +, ?, |
  • Range quantifiers {m,n}
  • Grouping via ()
This results in cleaner, more maintainable patterns.

Enabling ERE in grep

Use -E with grep or call the egrep command directly:
Sample output:

Quantifier Cheat Sheet

Optional Elements with ?

Make the preceding atom optional:
Because grep matches substrings by default, disabled? also finds disables unless you anchor (^, $) or use word boundaries (\b).

Zero or More with *

* allows the element to repeat any number of times:
Unbounded .* is greedy and may overmatch. Constrain it with character classes or quantifiers whenever possible.

Alternation with |

Select between multiple patterns:
Combine with ? to catch both forms:

Character Classes and Ranges

Define sets of allowed characters with []. Hyphens indicate ranges:

Building up a Device-Name Pattern

To match Linux device nodes under /dev while avoiding overmatching:
  1. Letters only:
  2. Append exactly one digit:
  3. Make the digit optional:
  4. Repeat letter+digit segments (e.g., tty0p0):
  5. Allow uppercase letters too:
Each refinement better aligns with real devices like /dev/sda, /dev/ttyS0, and /dev/tty0p0.

Sub-Expressions (Grouping)

Group subpatterns with parentheses so quantifiers apply to the entire unit:
The image shows a dark-themed interface with a command line on the left and a mathematical expression evaluation on the right, demonstrating the use of subexpressions with parentheses.

Negated Character Classes

Start a class with ^ to invert it:

Conclusion & Further Reading

Mastering EREs in grep, egrep, sed, and related tools empowers you to craft precise searches and avoid false positives. Practice your patterns interactively:

Watch Video