Python string.replace正则表达式

2024-06-30 15:53:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表单的参数文件:

parameter-name parameter-value

其中参数可以是任意顺序的,但每行只有一个参数。我想用一个新值替换一个参数的parameter-value

我正在使用一个行替换函数posted previously替换使用Python的^{}的行。例如,我使用的正则表达式可以在vim中工作,但在string.replace()中似乎不起作用。

下面是我使用的正则表达式:

line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))

其中"interfaceOpDataFile"是我要替换的参数名(/I表示不区分大小写),新的参数值是fileIn变量的内容。

有没有办法让Python识别这个正则表达式,或者有没有别的办法来完成这个任务?


Tags: 文件函数name表单参数parameter顺序value
3条回答

作为总结

import sys
import re

f = sys.argv[1]
find = sys.argv[2]
replace = sys.argv[3]
with open (f, "r") as myfile:
     s=myfile.read()
ret = re.sub(find,replace, s)   # <<< This is where the magic happens
print ret

您正在寻找re.sub函数。

import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced 

将打印axample atring

str.replace()v2v3不识别正则表达式。

要使用正则表达式执行替换,请使用re.sub()v2| v3

例如:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )

在循环中,最好先编译正则表达式:

import re

regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
    line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
    # do something with the updated line

相关问题 更多 >