Python string.replace正则表达式

Tro*_*ood 379 python regex replace

我有一个表单的参数文件

parameter-name parameter-value
Run Code Online (Sandbox Code Playgroud)

参数可以按任何顺序排列,但每行只有一个参数.我想用一个新值替换一个参数的参数值.

我正在使用之前发布的行替换函数(在Python中搜索并替换文件中的一行)来替换使用python的string.replace(pattern,subst)的行.我正在使用的正则表达式在vim中工作,但似乎不能在string.replace中工作.这是我正在使用的正则表达式:

line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))
Run Code Online (Sandbox Code Playgroud)

其中interfaceOpDataFile是我要替换的参数名称(/ i表示不区分大小写),新参数值是fileIn变量的内容.有没有办法让python识别这个正则表达式,否则还有另一种方法可以完成这个任务吗?

And*_*ark 521

str.replace() v2 | v3无法识别正则表达式.

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

例如:

import re

line = re.sub(
           r"(?i)^.*interfaceOpDataFile.*$", 
           "interfaceOpDataFile %s" % fileIn, 
           line
       )
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

  • 我必须传入`flags = re.MULTILINE`作为`re.sub`的最后一个参数才能使其工作,这是有道理的 - [在这里的文档中阅读](https:// docs. python.org/2/library/re.html#re.MULTILINE) (8认同)
  • 正则表达式汇编被缓存([docs](https://docs.python.org/3.6/library/re.html#re.compile)),因此甚至不需要编译.但正如您所示,如果编译,则在循环外编译. (8认同)

Jac*_*cki 346

您正在寻找re.sub功能.

import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced 
Run Code Online (Sandbox Code Playgroud)

将打印 axample atring


kpi*_*pie 14

作为总结

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
Run Code Online (Sandbox Code Playgroud)


Nel*_*z11 10

re.sub绝对是你要找的.所以你知道,你不需要锚和通配符.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
Run Code Online (Sandbox Code Playgroud)

将做同样的事情 - 匹配看起来像"interfaceOpDataFile"的第一个子串并替换它.

  • 啊,我误解了你用替换物做什么。如果每一对都在自己的线上,你仍然不需要明确的锚点。`re.sub(r"(?i)(interfaceOpDataFile).*", r'\1 UsefulFile', line)` 这将取整行,捕获参数名称,并将其添加回替换项。 (2认同)

归档时间:

查看次数:

715838 次

最近记录:

6 年,5 月 前