Merge pull request #11743 from renard/regex_escape-filter

Regex escape filter
This commit is contained in:
James Cammarata 2015-07-26 13:52:01 -04:00
commit a78ed39f93
2 changed files with 10 additions and 0 deletions

View file

@ -401,6 +401,11 @@ To replace text in a string with regex, use the "regex_replace" filter::
.. note:: If "regex_replace" filter is used with variables inside YAML arguments (as opposed to simpler 'key=value' arguments),
then you need to escape backreferences (e.g. ``\\1``) with 4 backslashes (``\\\\``) instead of 2 (``\\``).
To escape special characters within a regex, use the "regex_escape" filter::
# convert '^f.*o(.*)$' to '\^f\.\*o\(\.\*\)\$'
{{ '^f.*o(.*)$' | regex_escape() }}
A few useful filters are typically added with each new Ansible release. The development documentation shows
how to extend Ansible filters by writing your own as plugins, though in general, we encourage new ones
to be added to core so everyone can make use of them.

View file

@ -222,6 +222,10 @@ def version_compare(value, version, operator='eq', strict=False):
except Exception, e:
raise errors.AnsibleFilterError('Version comparison: %s' % e)
def regex_escape(string):
'''Escape all regular expressions special characters from STRING.'''
return re.escape(string)
@environmentfilter
def rand(environment, end, start=None, step=None):
r = SystemRandom()
@ -356,6 +360,7 @@ class FilterModule(object):
'search': search,
'regex': regex,
'regex_replace': regex_replace,
'regex_escape': regex_escape,
# ? : ;
'ternary': ternary,