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

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

我做错了什么?

最佳答案

您可以在消费模式中匹配 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 demo和一个 regex demo .

正则表达式详细信息:

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

关于python - 查找可能后跟小数点的所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44283412/

相关文章:

python - RegEx:如何匹配特定时间以上的时间码?

regex - 如何使用Perl查找与正则表达式匹配的所有字符串实例?

php - 如果网址有index.php/somefileOrsomedirectory,如何重定向

python - (Django) 类型对象 'User' 没有属性 'USERNAME_FIELD'

python - CherryPy 与 Django

c++ - boost 字符串匹配 DFA

使用正则表达式的 html 输入字段摆脱文件名的无效字符

python - OpenStack sdk 不会使用 keystone v3?

python - 如何在Scrapy中循环响应元素?

python - 如何在python中重新定义=?