令人惊讶的是
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
?
从perlretut:
来源:http://perldoc.perl.org/perlretut.html
Python的regex引擎是基于Perl的,所以行为类似。在
所以:
a=(([-+]?(\d*[.])?\d+)
外部捕获组,即2323.232323
==组1a=(([-+]?(\d*[.])?\d+)
内部捕获组,即(\d*[.])
,即2323.
==第2组b=([-+]?(\d*[.])?\d+)
外部捕获组,即23.23
==组3要获得所需的输出,请尝试以下操作:
输出:
^{pr2}$当捕获组变得复杂时,有时使用命名的捕获组会更容易。例如:
要创建名为
foo
的捕获组,可以使用(?<foo>...)
。要创建对它的反向引用,可以使用(?=foo)
。要获得它的内容,可以使用\g<foo>
。在这是您的正则表达式,当前分组为:
Formatted and tested:
输出:
^{pr2}$您不需要可选的捕获子组。
在将它们转换为簇组之后:
输出:
相关问题 更多 >
编程相关推荐