Lesson 10.1: Regular expressions: characters, classes and anchors
What a regular expression is and how it differs from shell wildcards, literal characters and metacharacters, the dot, bracket expressions with ranges and negation, POSIX character classes, the anchors ^ and $, and escaping a special character with a backslash. Every example runs through grep.
18 min
You will learn to
- Explain what a regular expression describes
- Tell regex metacharacters from shell wildcards
- Match one character of a set with [...] and exclude with [^...]
- Use POSIX classes such as [[:digit:]] and [[:upper:]]
- Anchor a pattern to the start or end of a line
- Escape . and other metacharacters
Key terms
- Regular expression (regex)
- A pattern that describes a set of strings. A program checks each line (or string) against it.
- Literal and metacharacter
- Most characters match themselves. Metacharacters have a special meaning: . [ ] ^ $ * \ (and in extended regex also + ? { } ( ) |).
- . (dot)
- Matches any single character.
- [...] bracket expression
- Matches one character from the list. Ranges like a-z and 0-9 are allowed; [^...] matches one character NOT in the list.
- POSIX classes
- Named sets used inside brackets: [:digit:] [:alpha:] [:alnum:] [:upper:] [:lower:] [:space:] [:punct:]. Write them with double brackets: [[:digit:]].
- Anchors ^ and $
- ^ matches the start of a line, $ the end. They match a position, not a character.
- Escaping
- A backslash before a metacharacter makes it literal: \. \* \[ \$.
← Scheduling tasks with cron · All lessons · Repetition, groups and alternatives →