簡體   English   中英

如何在python中使用re模塊匹配模式之間的線

[英]how to match lines between pattern using re module in python

我有一個包含多行的字符串(包含多行):

"Name=My name
Address=......
\##### To extract from here ####
line 1
line 2
line 3
\##### To extract till here ####
close"

如何提取"##### To extract *"字符串(包括模式)之間的行?

輸出應為以下內容:

\##### To extract from here ####
line 1
line 2
line 3

Ofir是正確的。 這是一個對應的示例:

>>> s = """... your example string ..."""
>>> marker1 = "\##### To extract from here ####"
>>> marker2 = "\##### To extract till here ####"
>>> a = s.find(marker1)
>>> b = s.find(marker2, a + len(marker1))
>>> print s[a:b]
\##### To extract from here ####
line 1
line 2
line 3
pat = re.compile('\\\\##### To extract from here ####'
                 '.*?'
                 '(?=\\\\##### To extract till here ####)',
                 re.DOTALL)

要么

pat = re.compile(r'\\##### To extract from here ####'
                 '.*?'
                 r'(?=\\##### To extract till here ####)',
                 re.DOTALL)

您不需要正則表達式,只需一個簡單的string.find就足夠了。

只需找到兩個字符串,然后輸出它們之間的輸入部分(通過對字符串進行切片)即可,注意避免輸出第一個字符串(即注意其長度)。

另外,您可以使用兩次調用string.split

>>> s
'\nName=My name\nAddress=......\n\\##### To extract from here ####\nline 1\nline 2\nline 3\n\\##### To extract till here ####\nclose'
>>> for o in s.split("\n"):
...     if "##" in o and not flag:
...        flag=1
...        continue
...     if flag and not "##" in o:
...        print o
...     if "##" in o and flag:
...        flag=0
...        continue
...
line 1
line 2
line 3

暫無
暫無

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

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