繁体   English   中英

在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匹配的字符串之前再添加一项检查。

我想,以取代text_to_searchreplacement_text只有一个减号-不存在诉讼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+'(.*)'也应该起作用。 希望能帮助到你

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM