使用 python re.sub 中的 () 在行内替换字符串
我想做一件非常简单的事情:
我有一行来自文本文件的内容,我知道它的确切格式。这行里有六个整数,用空格分开。
比如说:
line = '78 170 180 1 2 3'
我想做的是把第四个数字替换成另一个数字。这个替换的数字是通过一个变量传入的(也就是说,不是固定写死的):
num_replace_str
所以,我想要一段像这样的代码:
newline = re.sub(r'\d+\s\d+\s\d+\s(\d+)\s\d+\s\d+\s',num_replace_str,line)
这样就能得到如下的结果:
print newline
78 170 180 50 2 3
我只想替换第四个数字,我尝试过用括号把它们分组,然后用字符串 num_replace_str 来替换(在这个例子中,num_replace_str = '50')。
3 个回答
1
你需要使用捕获组来标记你想要保留的那部分内容,而不是你想要替换的部分。然后,你可以通过使用\n
来把第n
个组匹配到的内容复制到替换字符串中。
re.sub(r'^((?:\d+\s+){3})\d+', r'\1' + num_replace_str, line)
1
看起来你可以把这个字符串分开,插入新的值,然后再用' '.join
把它们拼接在一起。
split = line.split()
split[3] = str(50)
new_line = ' '.join(split)
举个例子:
>>> line = '78 170 180 1 2 3'
>>> split = line.split()
>>> split[3] = str(50)
>>> new_line = ' '.join(split)
>>> print new_line
78 170 180 50 2 3
不过要注意,这样做不会保留连续的空格……如果你需要保留这些空格,那用正则表达式可能会更合适。
1
你可以使用一种叫做正向前瞻断言的技巧。
>>> import re
>>> line = '78 170 180 1 2 3'
>>> num_replace_str = str(50)
>>> newline = re.sub(r'\d+(?=\s\d+\s\d+$)',num_replace_str,line)
>>> print newline
78 170 180 50 2 3
通过外部的regex
模块,
>>> import regex
>>> newline = regex.sub(r'(?<=^\d+\s\d+\s\d+\s)\d+',num_replace_str,line)
>>> print newline
78 170 180 50 2 3