簡體   English   中英

如何匹配使用正則表達式來匹配具有特定開始和結束模式的多行文本

[英]How do I match use regex to match multi-line text with specific starting and ending patterns

在 Python 正則表達式的幫助下,我試圖提取 [..] 之后並以 ;; 開頭的所有行。 特點。 請參閱下面的示例

sample_str = '''[TITLE]

[OPTIONS]
;;Options            Value
;;------------------ ------------
FLOW_UNITS           CFS
<MORE TEXT>

[PATTERNS]
;;Name           Type       Multipliers
;;-------------- ---------- -----------
;Daily pattern generated from time series '2-166:2-165 (obs)'.  Average value was 0.0485 MGD.
2-166:2-165_(obs)_Daily DAILY      1.011 1.008 1.06  0.908 1.072 0.998 0.942
<MORE TEXT>

[COORDINATES]
;;Node           X-Coord          Y-Coord         
;;-------------- ---------------- ----------------
<MORE TEXT>

[JUNCTIONS]
;;               Invert     Max.       Init.      Surcharge  Ponded    
;;Name           Elev.      Depth      Depth      Depth      Area      
;;-------------- ---------- ---------- ---------- ---------- ----------
1-1              837.85     15.25      0          0          0         
<MORE TEXT>  

[REPORT]
INPUT      YES
CONTROLS   NO
<MORE TEXT>
'''

我想得到一個列表

expected_result = [';;Options            Value\n;;------------------ ------------', ';;Name           Type       Multipliers\n;;-------------- ---------- -----------', ..]

我只能通過re.findall(r"(?<=\\]\\n);;.*", sample_str)獲得第一行。 嘗試通過像re.findall(r"(?<=\\]\\n);;.*\\n;;.*", sample_str, re.MULTILINE)添加\\n來添加更多行模式不起作用,因為模式對於我想要的文本並不統一。 我嘗試使用re.multiline來搜索所有文本,直到-\\n但我無法讓它像re.findall(r"(?<=\\]\\n);;.*-$", sample_str, re.MULTILINE)

有人可以幫我嗎!

對於它的價值,這很容易在沒有正則表達式的情況下實現:

input_str = '''...'''

flag = False
output = []

for line in input_str.splitlines():
    if not flag and line.startswith('[') and line.endswith(']'):
        flag = True
    elif flag and line.startswith(';;'):
        output.append(line)
    else:
        flag = False

print(output)

請注意,行結尾將丟失,因為.splitlines()吃掉它們。


如果輸入來自文件,則同樣簡單:

def parse_file(filename):
    flag = False
    with open(filename, 'r', encoding='utf8') as f:
        for line in f:
            if not flag and line.startswith('[') and line.endswith(']'):
                flag = True
            elif flag and line.startswith(';;'):
                yield line
            else:
                flag = False

你可以使用這樣的東西:

re.findall(r"^\[.*\]\n+((?:;;.*\n+)+)", sample_str, re.M)

這里是表達式的解釋


編輯:為模式添加了從行首開始的約束。 感謝您注意到@Wiktor Stribiżew

暫無
暫無

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

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