2017-07-09 39 views
-2

我想使用正則表達式在Python中像這樣正則表達式的數字賦值給變量

6 8 text text 8 text 10 text 

匹配和編號分配到單獨的數組變量有沒有辦法挑選基於關閉的順序他們陷入這樣的:

num1[i] = \d{1,2} should be just the 6 
num1[i] = \d{1,2} should be just the 8 
num1[i] = \d{1,2} should be just the second 8 
num1[i] = \d{1,2} should be just the 10 
+1

請給予更多解釋和細節,例如有預期結果的樣本輸入的幾個例子。 – Yunnosch

回答

1
import re 

s = '6 8 text text 8 text 10 text ' 
num1 = re.findall('\d+', s) 
+0

應該是'\ d +',所以它匹配'10'。另外,使用原始字符串。 – Barmar

0

據我理解你的問題,你想用re.findall()

import re 
text = '6 8 text text 8 text 10 text' 
strlist = re.findall('\d+', text) 
numlist = [int(i) for i in strlist] 

如果您想將找到的數字轉換爲實際整數,最後一步是必需的。另外請注意,我使用'\d+'來查找數字,因爲這比您的建議更一般。