匹配和替换浮点数re.sub公司

2024-10-01 22:42:42 发布

您现在位置:Python中文网/ 问答频道 /正文

令人惊讶的是

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)

^{pr2}$

为什么不产生

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


Tags: importrepatternprintpr2thisisathisisbthisisc
3条回答

从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的regex引擎是基于Perl的,所以行为类似。在

所以:

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

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

b=([-+]?(\d*[.])?\d+)外部捕获组,即23.23==组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)

输出:

^{pr2}$

当捕获组变得复杂时,有时使用命名的捕获组会更容易。例如:

pattern = r'a=(?P<thisisa>[-+]?(\d*[.])?\d+) b=(?P<thisisb>[-+]?(\d*[.])?\d+) c=(?P<thisisc>[-+]?(\d*[.])?\d+)'
tobereplacedwith = r'thisisb=\g<thisisb> thisisa=\g<thisisa> thisisc=\g<thisisc>'

要创建名为foo的捕获组,可以使用(?<foo>...)。要创建对它的反向引用,可以使用(?=foo)。要获得它的内容,可以使用\g<foo>。在

这是您的正则表达式,当前分组为:
Formatted and tested:

 a=
 (                             # (1 start)
      [-+]? 
      ( \d* [.] )?                  # (2)
      \d+ 
 )                             # (1 end)
 \ b=
 (                             # (3 start)
      [-+]? 
      ( \d* [.] )?                  # (4)
      \d+ 
 )                             # (3 end)
 \ c=
 (                             # (5 start)
      [-+]? 
      ( \d* [.] )?                  # (6)
      \d+ 
 )                             # (5 end)

输出:

^{pr2}$

您不需要可选的捕获子组。
在将它们转换为簇组之后:

 # a=([-+]?(?:\d*[.])?\d+) b=([-+]?(?:\d*[.])?\d+) c=([-+]?(?:\d*[.])?\d+)

 a=
 (                             # (1 start)
      [-+]? 
      (?: \d* [.] )?
      \d+ 
 )                             # (1 end)
 \ b=
 (                             # (2 start)
      [-+]? 
      (?: \d* [.] )?
      \d+ 
 )                             # (2 end)
 \ c=
 (                             # (3 start)
      [-+]? 
      (?: \d* [.] )?
      \d+ 
 )                             # (3 end)

输出:

 **  Grp 0 -  ( pos 0 , len 27 ) 
a=2323.232323 b=23.23 c=112  
 **  Grp 1 -  ( pos 2 , len 11 ) 
2323.232323  
 **  Grp 2 -  ( pos 16 , len 5 ) 
23.23  
 **  Grp 3 -  ( pos 24 , len 3 ) 
112  

相关问题 更多 >

    热门问题