我有一個這樣的序列'01 02 09 02 09 02 03 05 09 08 09 ',我想找到一個以 開頭01和結尾的序列,09中間可以有 1 到 9 個兩位數,例如02,03等04。這是我迄今為止嘗試過的。
我正在使用w{2}\s(w{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 '>
uj5u.com熱心網友回復:
您可以使用提取這些字串
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模式 and ,您可以從到最后一個re.search提取子字串(任何空格分隔兩個單詞字符塊)。0109
第二步[x[::-1] for x in re.findall(r'(?=\b(90.*?10$))', m.group()[::-1])]- 是反轉字串和模式以獲取所有重疊的匹配項09,01然后將它們反轉以獲得最終的字串。
如果您[::-1]在串列理解的末尾添加,您也可以反轉最終串列:print( [x[::-1] for x in re.findall(r'(?=\b(90.*?10$))', m.group()[::-1])][::-1] ).
uj5u.com熱心網友回復:
這將是一個對匹配元素進行后處理的非正則運算式答案:
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']
# ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/437269.html
