Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在 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)
在这里试试
正则表达式解释在这里
编辑: 这个正则表达式只会aaa在两者之间匹配一次XXX。
aaa
XXX