User123
User123

Reputation: 833

Regex expression to find strings between two strings in Python

I am trying to write a regular expression which returns a string which is between two other strings. For example: I want to get the string along with spaces which resides between the strings "15/08/2017" and "$610,000"

a='172 211 342    15/08/2017  TRANSFER OF LAND   $610,000        CASH & MTGE'

should return

"TRANSFER OF LAND"

Here is the expression I have pieced together so far:

re.search(r'15/08/2017(.*?)$610,000', a).group(1)

It doesn't return any matches. I think it is because we also need to consider spaces in the expression. Is there a way to find strings between two strings ignoring the spaces?

Upvotes: 0

Views: 74

Answers (3)

dawg
dawg

Reputation: 103744

>>> re.search(r'15/08/2017(.*)\$610,000',a).group(1)
'  TRANSFER OF LAND   '

Since $ is a regex metacharacter (standing for the end of a logical line), you need to escape it to use as a literal '$'.

Upvotes: 1

ic3b3rg
ic3b3rg

Reputation: 14927

Might be easier to use find:

a = '172 211 342 15/08/2017 TRANSFER OF LAND $610,000 CASH & MTGE'
b = '15/08/2017'
c = '$610,000'

a[a.find(b) + len(b):a.find(c)].strip()

'TRANSFER OF LAND'

Upvotes: 0

Rakesh
Rakesh

Reputation: 82755

Use Regex Lookbehind & Lookahead

Ex:

import re

a='172 211 342 15/08/2017 TRANSFER OF LAND $610,000 CASH & MTGE'
print(re.search(r"(?<=15/08/2017).*?(?=\$610,000)", a).group())

Output:

 TRANSFER OF LAND 

Upvotes: 2

Related Questions