2017-05-31 44 views
3

我正在尝试查找数字后跟小数点和另一个数字的所有组合。最后的决赛中小数点可能会丢失查找可能后跟小数点的所有数字

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

我在做什么错?

+3

're.findall('\ d \。\ d *',st)''+'至少需要一个右手数字,在最后一个例子中您没有这个数字。另外,消费数字使得下一个不匹配。 –

回答

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+数字
+0

@Echchama对不起,我有点迷失在你需要的东西里。如果你有'st ='2.1区域多路复用立体显示'作为输入,预期的输出是什么? 1和2的元组的列表? –

3

因为你无法比拟的两次相同的字符,你需要把捕获组前瞻断言里面不会消耗都在点右边的数字:

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