Python 3如何使用正则表达式在两点之间获取字符串?

sgp*_*sgp 6 regex string parsing python-3.x

如何使用正则表达式或Python 3中的任何其他库获取两点之间的字符串?

例如:Blah blah ABC要检索的字符串XYZ Blah Blah

ABC和XYZ是表示我必须检索的字符串的开头和结尾的变量.

Mar*_*ers 6

Use ABC and XYZ as anchors with look-behind and look-ahead assertions:

(?<=ABC).*?(?=XYZ)
Run Code Online (Sandbox Code Playgroud)

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

for matchedtext in re.findall(r'(?<=ABC).*?(?=XYZ)', inputtext):
Run Code Online (Sandbox Code Playgroud)

如果ABCXYZ是可变的,您想要使用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)
Run Code Online (Sandbox Code Playgroud)


jcr*_*udy 6

我想这就是你想要的:

import re
match = re.search('ABC(.*)XYZ','Blah blah ABC the string to be retrieved XYZ Blah Blah')
print match.group(1)
Run Code Online (Sandbox Code Playgroud)