我如何使用正则表达式匹配具有特定开始和结束模式的多行文本

问题描述 投票:0回答:1

[借助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)获得第一行。尝试通过像\n一样添加re.findall(r"(?<=\]\n);;.*\n;;.*", sample_str, re.MULTILINE)来添加更多的行模式,因为我想要的文本的模式不统一,因此不起作用。我尝试使用re.multiline搜索所有文本,直到-\n,但我无法将其用作re.findall(r"(?<=\]\n);;.*-$", sample_str, re.MULTILINE)

有人可以帮我吗!

python regex regex-lookarounds multiline
1个回答
0
投票

对于它的价值,完全不需要正则表达式,这很容易实现:

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)
© www.soinside.com 2019 - 2024. All rights reserved.