diff --git a/lib/ansible/runner/filter_plugins/core.py b/lib/ansible/runner/filter_plugins/core.py index 623e770dea..89c7312765 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) @@ -195,6 +204,7 @@ class FilterModule(object): 'match': match, 'search': search, 'regex': regex, + 'regex_replace': regex_replace, # list 'unique' : unique, diff --git a/test/TestFilters.py b/test/TestFilters.py index d850db4c3a..e79d4c8970 100644 --- a/test/TestFilters.py +++ b/test/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.