regex_replace¶
Collection Note
This module is part of the ansible.builtin collection. To install the collection, use:
Added in version2.0.
Synopsis¶
- Replace a substring defined by a regular expression with another defined by another regular expression based on the first match.
Parameters¶
| Parameter | Defaults / Choices | Comments |
|---|---|---|
| _input str required |
String to match against. | |
| _regex_match int required |
Regular expression string that defines the match. | |
| _regex_replace int required |
Regular expression string that defines the replacement. | |
| count int |
Maximum number of pattern occurrences to replace. If zero, replace all occurrences. Version Added: 2.17 |
|
| ignorecase bool |
Force the search to be case insensitive if V(True), case sensitive otherwise. | |
| mandatory_count int |
Except a certain number of replacements. Raises an error otherwise. If zero, ignore. Version Added: 2.17 |
|
| multiline bool |
Search across line endings if V(True), do not if otherwise. |
Notes¶
Note
- Maps to Python's C(re.sub).
- The substring matched by the group is accessible via the symbolic group name or the
\{number}special sequence. See examples section.
Examples¶
# whatami => 'able'
whatami: "{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}"
# commalocal => 'localhost, 80'
commalocal: "{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}"
# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('^(.ar)$', '#\\1', multiline=True, ignorecase=True) }}"
# Using inline regex flags instead of passing options to filter
# See https://docs.python.org/3/library/re.html for more information
# on inline regex flags
# piratecomment => '#CAR\n#tar\nfoo\n#bar\n'
piratecomment: "{{ 'CAR\ntar\nfoo\nbar\n' | regex_replace('(?im)^(.ar)$', '#\\1') }}"
# 'foo=bar=baz' => 'foo:bar=baz'
key_value: "{{ 'foo=bar=baz' | regex_replace('=', ':', count=1) }}"
Return Values¶
| Key | Data Type | Description | Returned |
|---|---|---|---|
| _value | str | String with substitution (or original if no match). |