Cal*_*vin 4 python regex replace find multiline
我正在用Python编写一个简单的版本更新程序,正则表达式引擎给了我巨大的麻烦.
特别是,即使使用re.MULTILINE选项,^和$也无法正确匹配.字符串匹配没有^和$,但没有其他喜悦.
如果你能发现我做错了什么,我将非常感谢你的帮助.
谢谢
target.c
somethingsomethingsomething
NOTICE_TYPE revision[] = "A_X1_01.20.00";
somethingsomethingsomething
Run Code Online (Sandbox Code Playgroud)
versionUpdate.py
fileName = "target.c"
newVersion = "01.20.01"
find = '^(\s+NOTICE_TYPE revision\[\] = "A_X1_)\d\d+\.\d\d+\.\d\d+(";)$'
replace = "\\1" + newVersion + "\\2"
file = open(fileName, "r")
fileContent = file.read()
file.close()
find_regexp = re.compile(find, re.MULTILINE)
file = open(fileName, "w")
file.write( find_regexp.sub(replace, fileContent) )
file.close()
Run Code Online (Sandbox Code Playgroud)
更新:感谢John和Ethan的有效观点.但是,如果我保留$,正则表达式仍然不匹配.一旦我删除$,它就会再次起作用.
将您的替换更改为:
replace = r'\g<1>' + newVersion + r'\2'
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是您的版本导致此问题:
replace = "\\101.20.01\\2"
Run Code Online (Sandbox Code Playgroud)
由于没有字段101,因此混淆了子调用.来自Python re模块的文档:
\ g <number>使用相应的组号; 因此,\ g 2等于\ 2,但在诸如\ g 2的替换中不是模糊的.\ 20将被解释为对组20的引用,而不是对组2的引用,后跟文字字符"0".