TASK [replace]
******************************************************************************
changed: [localhost] => (item=dogs:plays with mice)
ok: [localhost] => (item=dogs:plays with mice)
skipping: [localhost] => (item=dogs:does not play with mice)
ok: [localhost] => (item=dogs:plays with mice)
ok: [localhost] => (item=dogs:plays with mice)
skipping: [localhost] => (item=dogs:does not play with mice)
ok: [localhost] => (item=dogs:plays with mice)
> cat cats_dogs_file.txt
cats:plays with mice
cats:plays with mice
dogs:does not play with mice
cats:plays with mice
cats:plays with mice
dogs:does not play with mice
cats:plays with mice
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(.+):(plays? with)\s(.+)"
test_str = ("dogs:plays with mice\n"
"dogs:plays with mice\n"
"dogs:does not play with mice\n"
"dogs:plays with mice\n"
"dogs:plays with mice\n"
"dogs:does not play with mice\n"
"dogs:plays with mice\n\n"
"cats:plays with mice\n"
"cats:plays with mice\n"
"dogs:does not play with mice\n"
"cats:plays with mice\n"
"cats:plays with mice\n"
"dogs:does not play with mice\n"
"cats:plays with mice")
subst = "cats:\\2 \\3"
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
一个简单的解决方案是在线路上循环,并有条件地排除不应更换的线路。你知道吗
下面的剧本
给出(节略):
也许,在这里我们可以写一个表达式,找到所需输出的部分并替换它们。可能类似于:
JavaScript演示
Python测试
正则表达式
如果这不是您想要的表达式,您可以在regex101.com中修改/更改您的表达式。你知道吗
正则表达式电路
您还可以在jex.im中可视化您的表达式:
相关问题 更多 >
编程相关推荐