简体   繁体   English

Python re sub:以贪婪的方式捕获组

[英]Python re sub: capture group in greedy way

I am trying to extract digits in fallowing manner (bolded to be extracted)我正在尝试以休闲方式提取数字(粗体要提取)

0 -> 2 {2020-04-07 15:03} 0 -> 2 {2020-04-07 15:03}

0 -> 2 {2020-04-07 15:03} -> 67 {2020-04-07 15:20} 0 -> 2 {2020-04-07 15:03} -> 67 {2020-04-07 15:20}

With below code:使用以下代码:

a = '0 -> 2 {2020-04-07 15:03} -> 67 {2020-04-07 15:20}'
b = re.sub(r'^.*(\d+)\s({.+})$', r'\1', a)
print(b)
> 7

But I only get match on one (last) digit.但我只匹配一个(最后一个)数字。 Why greedeness is not working here?为什么贪婪在这里不起作用?

You can use:您可以使用:

re.sub(r'^.*\s(\d+)\s{.+}$', r'\1', a)

I added a \s before the capture number to make sure that it's preceded by a space.我在捕获号之前添加了一个\s以确保它前面有一个空格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM