我正在尝试修改文件中的某些行。我正在搜索文本并替换它。例如,在下面的代码中,我用vR33_ALAN*c替换了vR33_ALAN。
以下是我的测试用例代码
lines = ['x = vR32_ALEX - vR33_ALAN; \n',
'y = vR33_ALAN; \n']
text_to_search = 'vR33_ALAN'
replacement_text = 'vR33_ALAN*c'
for line in lines:
print(line.replace(text_to_search, replacement_text), end='')我可以成功地完成上面的任务。在替换与text_to_search匹配的字符串之前,我想再添加一个检查。
我只想在text_to_search中没有出现负-的情况下,用replacement_text替换text_to_search。
例如,我得到的输出是
x = vR32_ALEX - vR33_ALAN*c;
y = vR33_ALAN*c;所需输出:
x = vR32_ALEX - vR33_ALAN;
y = vR33_ALAN*c;我不确定如何实现上述目标。有什么建议吗?
发布于 2019-02-28 12:50:48
您可以使用或不使用正则表达式来执行此操作。您只需在text_to_search中添加'-'字符,然后使用find搜索新字符串
lines = ['x = vR32_ALEX - vR33_ALAN; \n',
'y = vR33_ALAN; \n']
text_to_search = 'vR33_ALAN'
replacement_text = 'vR33_ALAN*c'
for line in lines:
if line.find('- '+text_to_search)!=-1:
print(line)
else:
print(line.replace(text_to_search, replacement_text),end='') 或者,您可以按照建议使用re模块,因此您必须生成一个要搜索的模式,因为您要像以前一样查找'-'或添加text_to_search。(.*)将指定模式前后的字符并不重要。
import re
lines = ['x = vR32_ALEX - vR33_ALAN; \n',
'y = vR33_ALAN; \n']
for line in lines:
if re.match('(.*)'+' - '+'(.*)',line):
print(line)
else:
print(line.replace(text_to_search, replacement_text),end='') 模式'(.*)'+' - '+text_to_search+'(.*)'也应该可以工作。希望能有所帮助
发布于 2019-02-28 12:50:09
您可以将re.sub与负向回溯模式一起使用:
import re
lines = ['x = vR32_ALEX - vR33_ALAN; \n',
'y = vR33_ALAN; \n']
for line in lines:
print(re.sub(r'(?<!- )vR33_ALAN', 'vR33_ALAN*c', line), end='')这将输出以下内容:
x = vR32_ALEX - vR33_ALAN;
y = vR33_ALAN*c; https://stackoverflow.com/questions/54918220
复制相似问题