首页 > 解决方案 > Ansible 替换以 '$' 开头的模块正则表达式

问题描述

我正在尝试使用replaceAnsible 中的模块,但我不知道如何使用regexp.

我正在尝试匹配以字符开头的字符串,$但 ansible 一直说 he found unknown escape character '$'.

我知道ansible使用与python相同的正则表达式规则,但我也不能在python中这样做,你们知道怎么做吗?

我已经尝试过这些正则表达式规则:

^\$, [!^$],[!^$]\s*[!^$]

最后 3 条规则与以开头$的字符串匹配,但如果字符串不以 开头$,则也与这些字符串匹配。

最后 3 条规则的一些示例:

foo        doesn't match
$foo       match
$$$$       match
foo$       match
foo$bar    match

我只需要在这种情况下匹配:

foo
$foo       this case
$$$$       this case
foo$
foo$bar

标签: pythonregexpython-2.7replaceansible

解决方案


使用re.match

演示:

import re
l = ["foo", "$foo", "$$$$", "foo$", "foo$bar"]
for i in l:
    print(re.match("^\$", i))

输出:

None
<_sre.SRE_Match object at 0x0000000001D84578>
<_sre.SRE_Match object at 0x0000000001D84578>
None
None

在 Ansible 中尝试使用regex_search.


推荐阅读