簡體   English   中英

Python 正則表達式,用於匹配管道字符內的所有數字

[英]Python Regex for matching all numbers inside pipes characters

給定以下字符串:

string = "123|1*[123;abc;3;52m;|0|62|0|0|0|12|,399|;abc"

我想匹配一對管道字符中的所有數字。
所以在那種情況下,我希望matches的最終值等於[0, 62, 0, 0, 0, 12]

到目前為止,我嘗試了以下僅返回[0, 0, 0]的正則表達式:

matches = re.findall("\|(\d+)\|", string)

如果我用{1,}替換+ ,它只會返回[0, 0, 0] ,但是當我用{2,}替換+時,它會返回[62, 12]

所以我真的不明白我做錯了什么,謝謝你的幫助

問題是一旦你的表達式匹配 |0|,它就不能匹配相同的結束 | 作為開幕| 為下一個號碼。

嘗試使用這個正則表達式 - '\|(\d+)(?=\|)' 在這里, '(?=...)'部分稱為正向前瞻。 只有當它可以匹配該點的正則表達式時,匹配才會成功,但引擎不會消耗任何字符。

(?<=\|)\d+(?=\|)

打破它:

  • (?<=\|)是一個積極的向后看,它斷言捕獲的任何內容都必須在|之后。 象征
  • \d+表示只查找數字。 +告訴它繼續查找直到它停止。
  • (?<=\|)最后一個積極的前瞻告訴它在管道之間。

這是來自 regex101 的一些樣板代碼:

import re

regex = r"(?<=\|)\d+(?=\|)"

test_str = "123|1*[123;abc;3;52m;|0|62|0|0|0|12|,399|;abc"

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

for matchNum, match in enumerate(matches, start=1):
    
    print("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
    
    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1
        
        print("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

這是 output:

Match 2 was found at 24-26: 62
Match 3 was found at 27-28: 0
Match 4 was found at 29-30: 0
Match 5 was found at 31-32: 0
Match 6 was found at 33-35: 12

findall 1個pipe字"|" 不能同時屬於前面的數字和后面的數字。 (好吧,也許有前瞻)

以字符串"|0|62|0|"為例 . 第一部分"|0|" 匹配模式並添加到結果中。 然后模式匹配繼續使用字符串的 rest,即使用62|0| . 在此 substring 中找到第二個匹配項: |0| . 以這種方式找不到中間的數字 62。

我建議拆分字符串,忽略第一項和最后一項,因為它們不在兩個 pipe 字符之間。 然后檢查其余項目是否匹配"\d+" 您可以使用單線來完成,但這里分為幾個步驟:

s1 = "123|1*[123;abc;3;52m;|0|62|0|0|0|12|,399|;abc"
s2 = s1.split('|')
# ['123', '1*[123;abc;3;52m;', '0', '62', '0', '0', '0', '12', ',399', ';abc']
s3 = s2[1:-1]
s4 = [s for s in s3 if re.fullmatch('\d+', s)]
# ['0', '62', '0', '0', '0', '12']

我想是因為它跳過了中間的鄰居模式| 如果它找到了模式。 這是一個解決方法:

def get_nums(s):
    items = s.split('|')
    found = []
    for i, item in enumerate(items):
        if i and item.strip().isdigit():
            found.append(item)
    return found 

暫無
暫無

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

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