Regular expression foundations
Quick answer
A regular expression describes a text pattern. Unlike filename globbing, regex matches text using rules such as anchors, character classes and repetition. GNU grep supports basic (BRE) and extended (ERE) regular expressions.
Prepare the practice environment
Use the chapter fixture described in lab-fixtures/search-transform/README.md. Run setup as a normal user in a disposable Linux environment, enter the printed directory and check pwd. Every example assumes a fresh fixture. Commands omit the terminal prompt; outputs below are not commands.
How it works
^ and $ anchor the beginning and end of a line; . matches one character (not the line separator in ordinary line matching); [0-9] selects a digit in the C locale. In ERE, + repeats one or more times, ? makes an item optional, and (a|b) groups alternatives. BRE uses different escaping for several operators. Use grep -E for the ERE examples and -F for literal searches. A shell glob *.txt means a filename ending in .txt; the regex equivalent for a text suffix is .txt$.
Read ^ID-[0-9]+$ as four requirements: beginning of line, literal ID-, one or more digits, and end of line. It accepts ID-42 but rejects ID- and prefix-ID-42. Without the anchors, a matching substring could be enough. Shell quoting preserves the pattern text; grep then interprets its regular-expression operators.
Try the examples
Only lines beginning with ERROR match.
Expected stdout:
ERROR disk fullERROR retryAnchors reject prefixes and suffixes; + requires at least one digit.
Expected stdout:
ID-7ID-42The group allows either log level followed by a space.
Expected stdout:
INFO startERROR disk fullINFO checkERROR retryCommon mistakes
An unescaped dot is not a literal dot. Do not copy PCRE, BRE, ERE or shell glob syntax between tools without checking the dialect. Locale can change ranges and character classes.
Practice
Find only ID values containing exactly two digits using grep -E. Expected: ID-42.
Related references
Study: grep, sed. These are reference names, not deployed links.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Regular expression foundations — Knowledge Check
Apply the lesson concepts to the controlled text fixture.
What does ^ mean at the start of this regex?
What does [0-9]+ mean in ERE in C locale?
Which regex matches a literal .txt suffix?
Which flag selects ERE in grep?