正则表达式匹配指定分隔符之间的文本?(我自己无法得到它)

Gre*_*reg 2 regex

我一直在谷歌搜索并试图自己得到这个,但不能完全得到它...

问题:可以使用什么正则表达式来选择文本BETWEEN(但不包括)分隔符文本.举个例子:

Start Marker=ABC
Stop Marker=XYZ

---input---
This is the first line
And ABCfirst matched hereXYZ
and then
again ABCsecond matchXYZ
asdf
------------

---expected matches-----
[1] first matched here
[2] second match
------------------------
Run Code Online (Sandbox Code Playgroud)

谢谢

Cha*_*ffy 10

标准或扩展的正则表达式语法不能这样做,但它可以做的是创建匹配组,然后您可以选择.例如:

ABC(.*)XYZ
Run Code Online (Sandbox Code Playgroud)

将存储之间的任何ABCXYZ作为\1(或称为组1).

如果您正在使用PCRE(Perl兼容的正则表达式),也可以使用前瞻性和后瞻性断言 - 但是组是更便携且性能更好的解决方案.此外,如果您正在使用PCRE,则应使用*?以确保匹配非贪婪并在第一时间终止.

您可以在Python解释器中自己测试(Python正则表达式语法是PCRE派生的):

>>> import re
>>> input_str = '''
... This is the first line
... And ABC first matched hereXYZ
... and then
... again ABCsecond matchXYZ
... asdf
... '''
>>> re.findall('ABC(.*?)XYZ', input_str)
[' first matched here', 'second match']
Run Code Online (Sandbox Code Playgroud)