How do `regex_replace` and `regex_search` work?
IntermediateConceptJinja2, Conditionals and Loops
Answer
"{{ 'web-prod-01' | regex_replace('-[0-9]+$', '') }}" # web-prod
"{{ 'v1.4.2' | regex_replace('^v', '') }}" # 1.4.2
"{{ out.stdout | regex_search('version (\\d+\\.\\d+)', '\\1') }}" # ['1.4']
"{{ lines | map('regex_search', '^ERROR.*') | select | list }}"
regex_search returns the match, or an empty string (or None when no match depending on version) if nothing matches, so guard with | default. With a capture group argument it returns a list. In YAML double-quoted strings, escape backslashes (\\d), or use single quotes.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner