簡體   English   中英

正則表達式找到貪婪和懶惰的匹配以及所有介於兩者之間的匹配

[英]Regex find greedy and lazy matches and all in-between

我有一個像這樣的序列'01 02 09 02 09 02 03 05 09 08 09 ' ,我想找到一個以01開頭並以09結尾的序列,並且中間可以有 1 到 9 個兩位數,例如020304等。這是我到目前為止嘗試過的。

我正在使用w{2}\sw{2}用於匹配兩個數字,而\s用於空白)。 這可能會發生一到九次,從而導致(\w{2}\s){1,9} 整個正則表達式變為(01\s(\w{2}\s){1,9}09\s) 這將返回以下結果:

<regex.Match object; span=(0, 33), match='01 02 09 02 09 02 03 05 09 08 09 '>

如果我使用惰性量詞? ,它返回以下結果:

<regex.Match object; span=(0, 9), match='01 02 09 '>

我怎樣才能獲得中間的結果。 期望的結果將包括以下所有內容:

<regex.Match object; span=(0, 9), match='01 02 09 '>
<regex.Match object; span=(0, 15), match='01 02 09 02 09 '>
<regex.Match object; span=(0, 27), match='01 02 09 02 09 02 03 05 09 '>
<regex.Match object; span=(0, 33), match='01 02 09 02 09 02 03 05 09 08 09 '>

您可以使用提取這些字符串

import re
s = "01 02 09 02 09 02 03 05 09 08 09 "
m = re.search(r'01(?:\s\w{2})+\s09', s)
if m:
    print( [x[::-1] for x in re.findall(r'(?=\b(90.*?10$))', m.group()[::-1])] )
# => ['01 02 09 02 09 02 03 05 09 08 09', '01 02 09 02 09 02 03 05 09', '01 02 09 02 09', '01 02 09']

請參閱Python 演示

使用01(?:\s\w{2})+\s09模式和re.search ,您可以提取從01到最后一個09的子字符串(中間有任何空格分隔兩個單詞字符塊)。

第二步—— [x[::-1] for x in re.findall(r'(?=\b(90.*?10$))', m.group()[::-1])] - 是將字符串和模式反轉得到從0901的所有重疊匹配,然后反轉它們得到最終的字符串。

如果在列表理解的末尾添加[::-1] ,也可以反轉最終列表: print( [x[::-1] for x in re.findall(r'(?=\b(90.*?10$))', m.group()[::-1])][::-1] )

這將是一個非正則表達式的答案,它對匹配元素進行后處理:

s = '01 02 09 02 09 02 03 05 09 08 09 '.trim().split()
assert s[0] == '01'        \
   and s[-1] == '09'       \
   and (3 <= len(s) <= 11) \
   and len(s) == len([elem for elem in s if len(elem) == 2 and elem.isdigit() and elem[0] == '0'])
[s[:i+1] for i in sorted({s.index('09', i) for i in range(2,len(s))})]
# [
#    ['01', '02', '09'], 
#    ['01', '02', '09', '02', '09'], 
#    ['01', '02', '09', '02', '09', '02', '03', '05', '09'],
#    ['01', '02', '09', '02', '09', '02', '03', '05', '09', '08', '09']
# ]

暫無
暫無

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

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