Skip to content

This document is a WORK IN PROGRESS.
This is just a quick personal cheat sheet: treat its contents with caution!


Regular Expressions


Table of contents

TODO

Special characters

There are multiple types of regular expressions and the set of special characters depend on the particular type. Some of them are described below. In all the cases special characters are escaped by backslash \. E.g. to match [ you write \[ instead.

The characters which are special in some contexts, like ^ (special at the beginning of a (sub-)expression) can be escaped in all contexts.

In shell if you do not enclose the expression between single quotes you have to additionally escape the special characters for the shell in the already escaped regex. Example: Instead of '\[' you can write \\[ (alternatively: "\[" or "\\[") in Bourne compatible shells like bash but this is another story.

  • BRE

    • POSIX: Basic Regular Expressions
    • Commands: grep, sed
    • Special characters: .[\
    • Special in some contexts: *^$
    • Escape a string: "$(printf '%s' "$string" | sed 's/[.[\*^$]/\\&/g')"
  • ERE

    • POSIX: Extended Regular Expressions
    • Commands: grep -E, sed -r (GNU sed), sed -E (BSD sed)
    • Special characters: .[\(
    • Special in some contexts: *^$)+?{|
    • Escape a string: "$(printf '%s' "$string" | sed 's/[.[\*^$()+?{|]/\\&/g')"

If this cheat sheet has been useful to you, then please consider leaving a star here.