如何检查正则表达式然后才替换?



我有很多类似的文件包含

<id="1" status="one" group="first" city="CITY" ... >
<id="2" status="three" group="first" city="CITY" ... >
<id="3" status="two" group="first" city="CITY" ... >
<id="4" status="one" group="first" city="CITY" ... >

现在我想浏览所有文件并为所有文件添加bonus="yes",除了status="two"

<id="1" status="one" bonus="yes" group="first" city="CITY" ... >
<id="2" status="three" bonus="yes" group="first" city="CITY" ... >
<id="3" status="two" group="first" city="CITY" ... >
<id="4" status="one" bonus="yes" group="first" city="CITY" ... >

我有简单的正则表达式匹配,它有三个捕获组

  1. <id="_" status="__"
  2. group="___" city="___" ... >

我知道我可以在这样的地方添加行

with open(fileName) as currentFile:
content = (currentFile.read())
content = re.sub(regex, f"\1 {line_to_add} \2", content)
with open(fileName, "w") as f:
f.write(content)

如何执行检查何时status="two"通过它们?

with open(fileName) as currentFile:
content = currentFile.read()
# Here we set up a regex to match your potentially multi-line objects
line_regex = re.compile(r'<id.+[^<]*?n?>')
# Now we use re.findall to create a list of matched lines
lines = re.findall(line_regex, content)
# Continue as before
status_regex = re.compile(r'status="two"')
for line in content:
# This will only return `True` if `re.search()` matches
if not re.search(status_regex, line):
# Do your re.sub to add 'bonus="yes" to the line
with open(fileName, "w") as f:
for line in content:
f.write(content)

相关内容

最新更新