ansible Regular Expression Filters 正则表达式过滤器

注意事项:
正则表达式最好进行转义,如把 '\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 }}
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容