关于python:Re.sub对我不起作用

Re.sub not working for me

我试图获取re.sub来替换指定的模式,例如使用值

1
2
3
for lines in f:
    pattern='\\${2}'+key[0]+'\\${2}'
    re.search(pattern,lines)

这将返回找到模式的行。 例如,如果得到了这是测试返回值之一

这是$$ test $$

我遇到的问题是当我执行以下操作时

1
re.sub(pattern,key[1],lines)

没发生什么事。 我想念什么? 有关更多信息,请参见key[0]=testkey[1]=replace
所以我想做的是每当遇到" $$ test $$"时,它将用" replace"代替。 我可以轻松找到" $$ test $$",但是由于某些原因,re.sub不能代替它。


您正在将re.sub的结果分配回一个变量,对吗? 例如

1
lines = re.sub(pattern, key[1], lines)

这是一个字符串,因此无法更改(Python中的字符串是不可变的),因此将创建一个新字符串并将其返回给您。 如果不将其分配回名称,则会丢失该名称。


如果有文本,则可以直接在整个文本上运行re.sub(),如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import re

ss = '''that's a line
another line
a line to $$test$$
123456
here $$test$$ again
closing line'''


print(ss,'\
'
)

key = {0:'test', 1:'replace'}

regx = re.compile('\\$\\${[0]}\\$\\$'.format(key))

print( regx.sub(key[1],ss) )

如果您读取文件,则应该在运行re.sub()之前先读取整个文件并将其放入对象ss中,而不是逐行读取和替换

并且,如果您具有行列表,则必须按以下步骤处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 $$"的行将不会被修改:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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)

结果

1
["that's a line", 'another line', 'a line to $$test$$', '123456', 'here $$test$$ again', 'closing line']