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

Using find and replace text in python

我正在尝试修改文件中的某些行。我正在搜索文本并替换它。 例如,在下面的代码中,我将 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.

的字符串之前再添加一项检查

我想用 replacement_text 替换 text_to_search 只有当减号 - 不存在时 text_to_search.

例如, 我获得的输出是

x  = vR32_ALEX - vR33_ALAN*c;
y = vR33_ALAN*c;

期望的输出:

x  = vR32_ALEX - vR33_ALAN;
y = vR33_ALAN*c;

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

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

无论是否使用正则表达式,您都可以执行此操作。您只需将 '-' 字符添加到 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+'(.*)' 也应该有效。希望对你有帮助