查找可能后跟小数点的所有数字

时间:2017-05-31 11:20:30

标签: python regex

我试图找到一个数字后跟小数点和另一个数字的组合。可能缺少最后一个小数点

E.g., 
1.3.3 --> Here there are two combinations 1.3 and 3.3
1.3.3. --> Here there are two combinations 1.3 and 3.3

但是,当我运行以下代码时?

st='1.2.3 The Mismatch of Accommodation and Disparity and the Depths of Focus and of Field'
import re
re.findall('\d\.\d+',st)
['1.2']

我做错了什么?

2 个答案:

答案 0 :(得分:3)

因为您无法将相同的字符匹配两次,所以您需要将一个捕获组放在一个先行断言中,以便不消耗该点右侧的数字:

re.findall(r'(?=(\d+\.\d+))\d+\.', st)

答案 1 :(得分:3)

您可以在消费模式中匹配1+位数,并在正向前方中捕获小数部分,然后加入群组:

import re
st='1.2.3 The Mismatch of Accommodation and Disparity and the Depths of Focus and of Field'
print(["{}{}".format(x,y) for x,y in re.findall(r'(\d+)(?=(\.\d+))',st)])

请参阅Python demoregex demo

正则表达式详情

  • (\d+) - 第1组:一个或多个数字
  • (?=(\.\d+)) - 一个积极的前瞻,要求存在:
    • (\.\d+) - 第2组:一个点,然后是1+个数字
相关问题