2017-05-31 42 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)