Regular Expressions (Regex)
A regular expression (regex) is a compact pattern that describes a set of strings. A tool reads the pattern and tells you whether a text matches, which part matched, or replaces the match. Regex appears everywhere in cloud and automation work: grep and sed in the shell, Terraform functions, Ansible filters, Prometheus label matchers and input validation.
Key concepts #
- Literal and metacharacters:
abcmatches itself, while.,*,+,?,^,$,[ ],( ),{ },|and\have a special meaning. - Character class:
[a-z0-9]is one character from a set,\dis a digit,\wis a word character. - Quantifier: how many times:
*(0 or more),+(1 or more),?(0 or 1),{3,5}. - Anchor:
^start and$end of the text. - Group:
( )captures a part of the match for reuse. - Flavor: not every tool speaks the same dialect (POSIX, PCRE, RE2), so check what yours supports.
Learn it #
Follow the Regular expressions tutorial with examples and see regex in Terraform, Ansible and Prometheus.