我正在尝试修改一个文件,其中我希望用添加的参数替换一些括号。但是,使用re.search
首次成功停止甚至re.findall
都无济于事。
def Modify_Brackets(file_name):
input=open(file_name,"r")
output = open("help.txt", "w+")
for line in input:
text = input.read()
matches = re.findall(r'(rule).*([0-9]+).*:.*(\[.*\])(\s*)\-\-(\s*)(\[.*\])(\s*)\-\>(\s*)(\[.*])', text)
for m in matches:
Brackets= m[5][1:-1]
ModifiedBrackets = re.sub(r'\)',',changed)',Brackets)
newline = text.replace(m[5], ModifiedBrackets)
output.write(newline)
else:
output.write(text + "")
输入:
<some text>
rule abc1 : [some text]
--[ f(a,b), g(x,y) ]->
[some text]
<some text>
<some text>
rule abc2 : [some text]
--[ f(x,b), g(a,y) ]->
[some text]
目前的输出:
<some text>
rule abc1 : [some text]
--[ f(a,b,changed), g(x,y,changed) ]->
[some text]
<some text>
<some text>
rule abc2 : [some text]
--[ f(x,b), g(a,y) ]->
[some text]
预期输出:
<some text>
rule abc1 : [some text]
--[ f(a,b,changed), g(x,y,changed) ]->
[some text]
<some text>
<some text>
rule abc2 : [some text]
--[ f(x,b,changed), g(a,y,changed) ]->
[some text]
正如您所看到的,它仅适用于第一个规则,并在此之后停止。我希望对文件中存在的所有规则进行此更改。