How to get the string between two points using regex or any other library in Python 3?
For eg: Blah blah ABC the string to be retrieved XYZ Blah Blah
ABC and XYZ are variables which denote the start and end of the string which I have to retrieve.
How to get the string between two points using regex or any other library in Python 3?
For eg: Blah blah ABC the string to be retrieved XYZ Blah Blah
ABC and XYZ are variables which denote the start and end of the string which I have to retrieve.
I think this is what you want:
Use
ABC
andXYZ
as anchors with look-behind and look-ahead assertions:The
(?<=...)
look-behind assertion only matches at the location in the text that was preceded byABC
. Similarly,(?=XYZ)
matches at the location that is followed byXYZ
. Together they form two anchors that limit the.*
expression, which matches anything.You can find all such anchored pieces of text with
re.findall()
:If
ABC
andXYZ
are variable, you want to usere.escape()
(to prevent any of their content from being interpreted as regular expression syntax) on them and interpolate: