更新时间:2023-02-17 22:35:55
使用ABC
和XYZ
作为具有后向和前向断言的锚点:
Use ABC
and XYZ
as anchors with look-behind and look-ahead assertions:
(?<=ABC).*?(?=XYZ)
(?<=...)
后视断言仅在文本中以ABC
开头的位置匹配.同样,(?=XYZ)
在XYZ
后面的位置匹配.它们共同形成了两个锚点,这些锚点限制了.*
表达式,该表达式可以匹配任何内容.
The (?<=...)
look-behind assertion only matches at the location in the text that was preceded by ABC
. Similarly, (?=XYZ)
matches at the location that is followed by XYZ
. Together they form two anchors that limit the .*
expression, which matches anything.
您可以使用re.findall()
找到所有此类锚定文本:
You can find all such anchored pieces of text with re.findall()
:
for matchedtext in re.findall(r'(?<=ABC).*?(?=XYZ)', inputtext):
如果ABC
和XYZ
是变量,则要在它们上使用re.escape()
(以防止将其任何内容解释为正则表达式语法)并进行插值:
If ABC
and XYZ
are variable, you want to use re.escape()
(to prevent any of their content from being interpreted as regular expression syntax) on them and interpolate:
re.match(r'(?<={}).*?(?={})'.format(abc, xyz), inputtext)