簡體   English   中英

使用正則表達式從字符串 object 中提取數據到 Python

[英]Extract data from string object with regex into Python

我有這個字符串:

a = '91:99 OT (87:87)' 

我想把它分成:

['91', '99', '87', '87']

在我的例子中,數值可以從 01 到 999 不等,因此我必須使用正則表達式模塊。 我正在使用 Python。

抱歉,我找到了一個簡單的解決方案:

re.findall('[0-9]+', a)

我會回來:

['91', '99', '87', '87']

正則表達式是一個相當復雜的話題。 這個網站可以幫助很多https://regex101.com/ https://cheatography.com/davechild/cheat-sheets/regular-expressions/

我希望這是你正在尋找的答案

(\d+)(?=\s*)

第一捕獲組 (\d+)

  • \d匹配一個數字(相當於[0-9])
  • +在一次和無限次之間匹配前一個令牌,盡可能多次,根據需要回饋(貪婪)

正面前瞻(?=\s*)

  • \s匹配任何空白字符(相當於 [\r\n\t\f\v ])
  • *在零次和無限次之間匹配前一個令牌,盡可能多次,根據需要回饋(貪心)
    import re

regex = r"(\d+)(?=\s*)"

test_str = "a = '91:99 OT (87:87)'"

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):
    
    print (" F{matchNum} : {match}".format(matchNum = matchNum, match = match.group()))
    
    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM