diff --git a/lib/ansible/runner/filter_plugins/core.py b/lib/ansible/runner/filter_plugins/core.py index a99b17f67a1..a511b18bcb1 100644 --- a/lib/ansible/runner/filter_plugins/core.py +++ b/lib/ansible/runner/filter_plugins/core.py @@ -127,6 +127,15 @@ def search(value, pattern='', ignorecase=False): ''' Perform a `re.search` returning a boolean ''' return regex(value, pattern, ignorecase, 'search') +def regex_replace(value='', pattern='', replacement='', ignorecase=False): + ''' Perform a `re.sub` returning a string ''' + if ignorecase: + flags = re.I + else: + flags = 0 + _re = re.compile(pattern, flags=flags) + return _re.sub(replacement, value) + def unique(a): return set(a) @@ -196,6 +205,7 @@ class FilterModule(object): 'match': match, 'search': search, 'regex': regex, + 'regex_replace': regex_replace, # list 'unique' : unique, diff --git a/test/units/TestFilters.py b/test/units/TestFilters.py index d850db4c3a3..e79d4c8970d 100644 --- a/test/units/TestFilters.py +++ b/test/units/TestFilters.py @@ -116,6 +116,21 @@ class TestFilters(unittest.TestCase): True) assert a == True + def test_regex_replace_case_sensitive(self): + a = ansible.runner.filter_plugins.core.regex_replace('ansible', '^a.*i(.*)$', + 'a\\1') + assert a == 'able' + + def test_regex_replace_case_insensitive(self): + a = ansible.runner.filter_plugins.core.regex_replace('ansible', '^A.*I(.*)$', + 'a\\1', True) + assert a == 'able' + + def test_regex_replace_no_match(self): + a = ansible.runner.filter_plugins.core.regex_replace('ansible', '^b.*i(.*)$', + 'a\\1') + assert a == 'ansible' + #def test_filters(self): # this test is pretty low level using a playbook, hence I am disabling it for now -- MPD.