ansible regex替换所有匹配的string1,排除string2

2024-04-24 12:50:55 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
2条回答

一个简单的解决方案是在线路上循环,并有条件地排除不应更换的线路。你知道吗

下面的剧本

tasks:
  - replace:
      path: "{{ file_to_update }}"
      regexp: "{{ item }}"
      replace: "{{ item|regex_replace(from_name, to_name) }}"
    with_lines: "cat {{ file_to_update }}"
    when: exclude not in item

给出(节略):

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

也许,在这里我们可以写一个表达式,找到所需输出的部分并替换它们。可能类似于:

(.+):(plays? with)\s(.+)

enter image description here

JavaScript演示

Python测试

# 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.

正则表达式

如果这不是您想要的表达式,您可以在regex101.com中修改/更改您的表达式。你知道吗

正则表达式电路

您还可以在jex.im中可视化您的表达式:

enter image description here

相关问题 更多 >