我正在尝试查找一个数字后跟小数点和另一个数字的所有组合。最后一位小数点可能丢失
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/