简体   繁体   English

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

[英]Finding all digits that may be followed by a decimal point

I am trying to findall combinations of of a digit followed by decimal point and another digit. 我试图找到一个数字后跟小数点和另一个数字的组合。 The last final decimal point may be missing 可能缺少最后一个最后的小数点

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

However, when I run the following code? 但是,当我运行以下代码?

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']

What am I doing wrong? 我究竟做错了什么?

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

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

You may match 1+ digits in the consuming pattern and capture the fractional part inside a positive lookahead, then join the groups: 您可以在消费模式中匹配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)])

See the Python demo and a regex demo . 请参阅Python演示正则表达式演示

Regex details : 正则表达式详细信息

  • (\\d+) - Group 1: one or more digits (\\d+) - 第1组:一个或多个数字
  • (?=(\\.\\d+)) - a positive lookahead that requires the presence of: (?=(\\.\\d+)) - 一个积极的前瞻,需要存在:
    • (\\.\\d+) - Group 2: a dot and then 1+ digits (\\.\\d+) - 第2组:一个点,然后是1+个数字

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

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