Regular expressions, part 2: classes and groups with egrep
Character classes like [0-9], alternatives with |, grouping with ( ) and the +, ? and {n} repetitions of extended regular expressions.
What you will learn
- Write character classes with brackets, ranges, negation and the POSIX names like [:digit:].
- Use grep -E (egrep) for |, ( ), +, ? and {n,m}.
- Tell basic from extended syntax and know when each applies.
The dot matches any character, which is often too generous. Character classes let you say "a digit", "a vowel" or "anything but a space". And when you want "this or that", or to repeat a whole group rather than a single character, you need the extended regular expression syntax, which grep -E enables; egrep is a traditional alias for the same thing, and this VM has both.
Character classes
Square brackets match one character from the set inside. [aeiou] is a vowel, [0-9] a digit, [a-zA-Z] a letter, [^0-9] anything that is *not* a digit (the caret negates when it is first inside the brackets). POSIX names make this readable and locale-safe: [[:digit:]], [[:alpha:]], [[:space:]], [[:upper:]]; the double brackets are correct, the inner pair is the class name and the outer pair the set. Inside brackets most special characters lose their meaning, so [.] is a literal dot.
Classes work in basic grep too, and combine with *: grep '^[0-9]*