Re.sub对我无效
我正在尝试使用 re.sub 来替换一个特定的模式,比如说
for lines in f:
pattern='\${2}'+key[0]+'\${2}'
re.search(pattern,lines)
这段代码会返回找到模式的那一行。例如,这里有一个测试返回值:
这是一个 $$test$$
我遇到的问题是,当我这样做的时候
re.sub(pattern,key[1],lines)
什么也没有发生。我漏掉了什么呢?更多信息是 key[0]=test 和 key[1]=replace,所以我想要做的是每当遇到 "$$test$$" 时,它会被替换成 "replace"。我找到 "$$test$$" 没有问题,但不知道为什么 re.sub 没有进行替换。
相关问题:
2 个回答
1
如果你有一段文本,可以直接对整段文本使用 re.sub(),方法如下:
import re
ss = '''that's a line
another line
a line to $$test$$
123456
here $$test$$ again
closing line'''
print(ss,'\n')
key = {0:'test', 1:'replace'}
regx = re.compile('\$\${[0]}\$\$'.format(key))
print( regx.sub(key[1],ss) )
.
如果你是从文件中读取内容,建议先把整个文件的内容读进一个对象ss里,然后再对这个对象使用 re.sub(),而不是一行一行地读取和替换。
.
如果你有一组行(也就是一行一行的文本),你需要这样处理:
import re
key = {0:'test', 1:'replace'}
regx = re.compile('\$\${[0]}\$\$'.format(key))
lines = ["that's a line",
'another line',
'a line to $$test$$',
'123456',
'here $$test$$ again',
'closing line']
for i,line in enumerate(lines):
lines[i] = regx.sub(key[1],line)
否则,包含 '$$test$$' 的那一行就不会被修改:
import re
key = {0:'test', 1:'replace'}
regx = re.compile('\$\${[0]}\$\$'.format(key))
lines = ["that's a line",
'another line',
'a line to $$test$$',
'123456',
'here $$test$$ again',
'closing line']
for line in lines:
line = regx.sub(key[1],line)
print (lines)
结果
["that's a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line']
22
你是把re.sub的结果重新赋值给一个变量,对吧?比如:
lines = re.sub(pattern, key[1], lines)
这是一个字符串,所以它是不能被直接修改的(在Python中,字符串是不可变的),因此会创建一个新的字符串并返回给你。如果你不把这个新字符串再赋值给一个变量,你就会失去它。