Regular Expressions (Regex)

· 1 min read · Concepts and Practices · Concept

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: abc matches itself, while ., *, +, ?, ^, $, [ ], ( ), { }, | and \ have a special meaning.
  • Character class: [a-z0-9] is one character from a set, \d is a digit, \w is 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.

#Regex #Linux