注意事项:
正则表达式最好进行转义,如把'\d'
写成'\\d'
, 否则可能会报语法错误found unknown escape character
regex_search
使用正则表达式搜索字符串:
# search for "foo" in "foobar"
{{ 'foobar' | regex_search('(foo)') }}
# will return empty if it cannot find a match 没有匹配到返回空
{{ 'ansible' | regex_search('(foobar)') }}
# case insensitive search in multiline mode 和python正则一样,支持多行及忽略大小写
{{ 'foo\nBAR' | regex_search("^bar", multiline=True, ignorecase=True) }}
regex_findall
类似于re.findall 返回所有匹配结果的列表
# Return a list of all IPv4 addresses in the string
{{ 'Some DNS servers are 8.8.8.8 and 8.8.4.4' | regex_findall('\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b') }}
regex_replace
用于替换匹配的字符串,可用来动态生成新的字符串
# convert "ansible" to "able"
{{ 'ansible' | regex_replace('^a.*i(.*)$', 'a\\1') }}
# convert "foobar" to "bar"
{{ 'foobar' | regex_replace('^f.*o(.*)$', '\\1') }}
# convert "localhost:80" to "localhost, 80" using named groups 使用组进行替换
{{ 'localhost:80' | regex_replace('^(?P<host>.+):(?P<port>\\d+)$', '\\g<host>, \\g<port>') }}
# convert "localhost:80" to "localhost"
{{ 'localhost:80' | regex_replace(':80') }}
# add "https://" prefix to each item in a list
{{ hosts | map('regex_replace', '^(.*)$', 'https://\\1') | list }}