Skip to main content
 首页 » 编程设计

python之使用 re.sub 匹配和替换 float

2025年05月04日31lyhabc

令人惊讶的是,

的输出
import re 
s = "a=2323.232323 b=23.23 c=112  d=12" 
pattern = r'a=([-+]?(\d*[.])?\d+) b=([-+]?(\d*[.])?\d+) c=([-+]?(\d*[.])?\d+)' 
tobereplacedwith = r'thisisb=\2 thisisa=\1 thisisc=\3' 
print re.sub(pattern, tobereplacedwith, s) 

是

thisisb=2323. thisisa=2323.232323 thisisc=23.23  d=12 

为什么这个不产生

thisisb=23.23 thisisa=2323.232323 thisisc=112  d=12 

?

请您参考如下方法:

来自 perlretut:

If the groupings in a regexp are nested, $1 gets the group with the leftmost opening parenthesis, $2 the next opening parenthesis, etc.

来源:http://perldoc.perl.org/perlretut.html

Python 的正则表达式引擎基于 Perl 的,因此行为相似。

所以:

a=(([-+]?(\d*[.])?\d+) 外捕获组即 2323.232323 == Group 1

a=(([-+]?(\d*[.])?\d+) 内部捕获组即 (\d*[.])即 2323. == 第 2 组

b=([-+]?(\d*[.])?\d+) 外捕获组即 23.23 == Group 3

要得到你想要的输出,试试这个:

import re 
s = "a=2323.232323 b=23.23 c=112  d=12" 
pattern = r'a=([-+]?(\d*[.])?\d+) b=([-+]?(\d*[.])?\d+) c=([-+]?(\d*)([.]\d*)?)' 
tobereplacedwith = r'thisisb=\3 thisisa=\1 thisisc=\6' 
print re.sub(pattern, tobereplacedwith, s) 

输出:

thisisb=23.23 thisisa=2323.232323 thisisc=112  d=12