在Python中用re.sub和re.findall

时间:2018-06-12 14:51:07

标签: python regex

我使用正则表达式在某些字符后找到一些数字。我遇到的问题是,当我尝试替换字符串时,Python并没有忽略括号外的内容,但是当我使用re.findall时它会这样做。这是一个示例,我想在g=之后替换数字:

str = '999.33 This is an example g= 9.81 with numbers 32 in bewteen 5555'
test_find = re.findall('=\s(\d+\.?\d+)', str)
test_sub = re.sub('=\s(\d+\.?\d+)', '10', str)
print(test_find, test_sub)

有了这个我得到:

['9.81'] 999.33 This is an example g10 with numbers 32 in bewteen

但我想将g= 9.81替换为g= 10。 我不明白为什么它与re.findall合作。

1 个答案:

答案 0 :(得分:0)

尝试:

import re
str = '999.33 This is an example g= 9.81 with numbers 32 in bewteen 5555'
print( re.sub(r'(?<=\=)(\s+\d+\.?\d+)', '10', str) )   #Lookbehind

<强>输出:

999.33 This is an example g=10 with numbers 32 in bewteen 5555
相关问题