在python中使用查找和替换文本

时间:2019-02-28 04:02:53

标签: python str-replace

我正在尝试修改文件中存在的某些行。我正在搜索文本并替换它。 例如,在以下代码中,我将vR33_ALAN替换为vR33_ALAN*c

这是我的测试用例代码

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;

我不确定如何实现上述目标。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您可以将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; 

答案 1 :(得分:1)

您可以使用和不使用正则表达式来执行该操作。您只需将'-'字符添加到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+'(.*)'也应该起作用。希望对您有帮助