Ansible regex_search & regex_replace Filters: Pattern Matching Guide
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
Complete guide to Ansible regex_search and regex_replace filters. Extract text with regex patterns, find and replace strings, validate formats, parse log files, and use capture groups with practical examples.
Ansible's regex_search and regex_replace filters let you extract and transform text using regular expressions — parse version numbers, validate formats, clean strings, and extract values from command output.
regex_search: Find and Extract
Returns the first match (or None if no match):
Capture Groups
regex_replace: Find and Replace
Common Patterns
Parse Command Output
Validate Email Format
Extract IP from Text
Clean Whitespace
Parse Key=Value Pairs
Strip HTML Tags
Case-Insensitive Matching
Multiline Matching
Using regex in when Conditions
regex_findall: All Matches
regex_search vs match vs search
FAQ
Why does regex_search return None instead of matching?
Common causes: not escaping backslashes (use \\d not \d in YAML), or the pattern expects start/end anchors. Test your regex at regex101.com first, then double-escape for YAML.
How do I use capture groups with regex_search?
Pass the group reference as additional arguments: regex_search('pattern(group)', '\\1'). This returns a list, so use | first to get the string value.
What regex flavor does Ansible use?
Python re module — supports \d, \w, \s, lookahead (?=...), lookbehind (?<=...), and named groups (?P
How do I make regex_replace work on multiline strings?
Add multiline=True for ^ and $ to match line boundaries, or dotall=True for . to match newlines.
Conclusion
Use regex_search to extract data from strings, regex_replace to transform strings, and regex_findall to find all occurrences. Always double-escape backslashes in YAML (\\d not \d). For simple contains/startswith checks, prefer is search and is match tests — they're more readable than regex_search for boolean conditions.
Related Articles • Ansible map vs selectattr vs json_query • Ansible Jinja2 Templates Guide • Ansible lineinfile Module Cookbook • Ansible Conditionals Guide
Category: troubleshooting