0

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?

1
  • It is because you need to escape $. Commented Dec 19, 2018 at 6:34

3 Answers 3

2

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 
Sign up to request clarification or add additional context in comments.

Comments

1
>>> 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 '$'.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.