简体   繁体   English

如何在python中使用re模块匹配模式之间的线

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

I have a string (with multiple lines) which contains the following: 我有一个包含多行的字符串(包含多行):

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

How do I extract the lines between "##### To extract *" string including the pattern as well? 如何提取"##### To extract *"字符串(包括模式)之间的行?

Output should be the following: 输出应为以下内容:

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

Ofir is right. Ofir是正确的。 Here's a corresponding example: 这是一个对应的示例:

>>> 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)

or 要么

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

You don't need regular expressions for that, a simple string.find would suffice. 您不需要正则表达式,只需一个简单的string.find就足够了。

Simply find both strings, and output the portion of the input between them (by slicing the string), taking care to avoid outputting the first string (ie noting its length). 只需找到两个字符串,然后输出它们之间的输入部分(通过对字符串进行切片)即可,注意避免输出第一个字符串(即注意其长度)。

Alternatively, you can use two calls to string.split . 另外,您可以使用两次调用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