如何在Python中使用re模块匹配模式间的行

1 投票
4 回答
3744 浏览
提问于 2025-04-16 12:22

我有一个包含多行的字符串,里面有以下内容:

"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

4 个回答

2

其实你不需要用正则表达式来解决这个问题,简单的用 string.find 就可以了。

你只需要找到这两个字符串,然后输出它们之间的部分内容(可以通过切片来实现),记得不要输出第一个字符串的内容(也就是要注意它的长度)。

另外,你也可以用两次 string.split 来处理。

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

撰写回答