python 中两个字符串之间的匹配模式

Match pattern between two character strings in python

我在 python 中使用 re 模块,我想匹配两个字符串之间的字符串。假设我有以下字符串:

aaa

XXX
bbb
aaa
bbb

XXX

我想匹配 aaa 字符串,但只匹配 XXX 字符串中的字符串。在上面的例子中只会匹配第二个 aaa 字符串,因为它在两个 XXX 字符串中。

如何在 python 中实施?

这是一个允许您执行此操作的正则表达式。

import re
string = """aaa
XXX
bbb
aaa
bbb

XXX
"""
regex = "(?<=XXX)(.*\s*)*(aaa)(.*\s*)*(?=XXX)"
found = re.findall(regex, string)
print(found)

试一试here

正则表达式解释here

编辑: 此正则表达式只会在两个 XXX.

之间匹配一次 aaa