Python 如何检查正则表达式并仅替换?
我有很多类似的文件,其中包含Python 如何检查正则表达式并仅替换?,python,regex,Python,Regex,我有很多类似的文件,其中包含 <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" ... &g
<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" ... >
我有一个简单的正则表达式匹配,它有三个捕获组
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)
content=currentFile.read()
#这里我们设置了一个正则表达式来匹配可能的多行对象
line_regex=re.compile(r’我将使用currentFile.read()
,而不是使用currentFile.readlines()将整个文件读入一个长字符串
将文件的每一行放入一个单独的列表项中。然后使用for
循环遍历文件中的每一行,执行正则表达式测试查看是否status=“two”
,如果不是,则执行re.sub([…])
@ResetACK您好,谢谢,但这在我的情况下是不可能的,请阅读我对答案的评论,您能提供另一个选项/解决方法吗?您并不需要正则表达式来搜索status=“two”
。不需要,但为了符合OP使用正则表达式的主题,我想我会使用它:)我会使用readlines()但关键是,每个条目都不是一行(id=1可以是5行,id=2-3id=3-5等等,status=“two”可以在任何一行中),因此我不能指定行数或逐行读取,应该打开完整的文件。我本想更改regex以捕获除status=“2”之外的所有内容,但这将是一个临时解决方案。我想制作一个命令行工具,用户可以在其中添加异常,而程序不会向该条目写入新的“功能”。@Arthur请看我编辑的答案-现在,我们在执行一些正则表达式以匹配多行输入之前,一次读完该文件,然后剩下的都是一样的
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)