Terminal · foundation

Regular expressions

A regular expression is a pattern language for matching text, with exact syntax and features determined by the selected regex dialect and tool mode.

Why it matters

Regex supports precise search and validation, but unanchored patterns, shell interpretation, and dialect differences often cause plausible-looking mistakes.

Mental model

How to reason about regular expressions

A matcher searches for a substring unless anchors or an API require a whole-string match; operators describe alternatives, repetition, grouping, and character sets.

Analogy

A regex is a stencil for character sequences: unless attached to an edge with an anchor, the stencil may fit somewhere inside a larger line.

Examples

See the boundary, not just the happy path

Worked example · Match a complete identifier

grep -E '^[[:alpha:]_][[:alnum:]_]*$' names.txt

^ and $ constrain the whole line, the first class rejects a leading digit, and * allows zero or more later identifier characters.

Worked example · Choose alternatives

grep -E 'timeout|connection refused' app.log

Extended-regex alternation selects lines containing either phrase; quoting prevents the shell from treating | as a pipeline operator.

Useful contrast · Glob versus regex star

Glob: *.log    Regex: .*\.log$

A glob star matches an arbitrary filename string, while regex * repeats the preceding atom and therefore needs . before it to match arbitrary characters.

Common mistakes

Misconceptions to remove early

Leaving a pattern unquoted in the shell

The shell may expand metacharacters before grep sees them; quote regex arguments unless deliberate shell expansion is required.

Assuming one universal regex dialect

Basic, extended, Perl-compatible, and language-specific engines differ in operators and behavior, so state the tool and mode.

Quick check

Can you predict the result?

1. What do ^ and $ normally add to a line-oriented grep pattern?
  • Anchors for the start and end of the line
  • Literal caret and dollar characters in every mode
  • Case-insensitive matching
Answer: Anchors for the start and end of the line
2. Why must 'cat|dog' be quoted in a grep -E command?
Answer: Without quotes, the shell interprets | as a pipeline operator instead of passing it to the regex engine.

Keep building

Authoritative references

Make the idea retrievable.

Study this concept with spaced repetition, next to the commands where you use it.

Get Terminaster