[英]Regular expression to extract numbers around a slash "/"
我試圖以類似"**/*,**/*"
的格式提取數字。
例如,對於字符串"272/3,65/5"
,我想得到一個list = [272,3,65,5]
我嘗試使用\\d*/
和/\\d*
分別提取 272,65 和 3,5,但我想知道是否有一種方法可以直接獲取上面顯示的列表。 謝謝!
#importing regular expression module
import re
# input string
s = "272/3,65/5"
# with findall method we can extract text by given format
result = re.findall('\d+',s)
print(result) # ['272', '3', '65', '5']
['272', '3', '65', '5']
其中 \\d 表示匹配給定輸入中的數字,如果我們使用 \\d 它會給出如下輸出
result = re.findall('\d',s)
['2', '7', '2', '3', '6', '5', '5']
所以我們應該在可能的匹配中使用 \\d+ where + 匹配到失敗匹配
您可以使用[0-9]
表示單個十進制數字。 所以編寫正則表達式的更好方法是[0-9]*/?[0-9]+,[0-9]+/?[0-9]*
。 我假設您正在嘗試匹配小數點,例如5,2/3
、 23242/234,23
或0,0
。
[0-9]*/?[0-9]+,[0-9]+/?[0-9]*
主要成分分解:
[0-9]*
匹配 0 個或多個數字/?
可選匹配'/'
[0-9]+
至少匹配一位數字我最喜歡的調試正則表達式的工具是https://regex101.com/,因為它解釋了每個運算符的含義,並向您展示了正則表達式在您編寫時如何在您選擇的樣本上執行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.