Python 3如何使用正则表达式在两点之间获取字符串? [英] Python 3 How to get string between two points using regex?
问题描述
如何使用regex或Python 3中的任何其他库在两点之间获取字符串?
How to get the string between two points using regex or any other library in Python 3?
例如: Blah blah ABC要检索的字符串XYZ Blah Blah
For eg: Blah blah ABC the string to be retrieved XYZ Blah Blah
ABC和XYZ是表示我必须检索的字符串的开始和结束的变量.
ABC and XYZ are variables which denote the start and end of the string which I have to retrieve.
推荐答案
使用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)
这篇关于Python 3如何使用正则表达式在两点之间获取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!