Python regex to return characters after a search term

Viewed 64

I'm trying to use regex to extract information from some strings

I can find the text using re.search, but how to get the information provided after the search term?

In the format Ref number ABC123456Ref date 01.01.2000 how can I return ABC123456 and 01.01.2000?

import re
reqd_info = "Ref number"
test_text = 'Ref number ABC123456Ref date 01.01.2000'
res = re.search(reqd_info, test_text)

3 Answers

You can achieve this effect by changing your regular expresssion to

<YOUR SEARCHTERM>(.*)

this way the result has a group which contains the left over information.

You can use groups in your regular expression, then use re.findall to get a list of tuples containing the matched groups.

In [1]: import re

In [2]: test_text = 'Ref number ABC123456Ref date 01.01.2000'

In [3]: re.findall("Ref number (.*)Ref date (.*)", test_text)
Out[3]: [('ABC123456', '01.01.2000')]

In [4]: [[number, date]] = re.findall("Ref number (.*)Ref date (.*)", test_text)

In [5]: number
Out[5]: 'ABC123456'

In [6]: date
Out[6]: '01.01.2000'

I'm not familiar with regex, but it can be done without, too:

test_text = 'Ref number ABC123456Ref date 01.01.2000'
reqd_info = "Ref number"

text = test_text.replace(reqd_info, "").strip() # get rid of Ref number and strip leading and trailing spaces
ref_number, _, date = text.split(" ") # split at spaces

print(ref_number, date)

Output:

ABC123456Ref 01.01.2000

The above code can be reduced to one line, if you want short code:

test_text = 'Ref number ABC123456Ref date 01.01.2000'
reqd_info = "Ref number"

print(*test_text.replace(reqd_info, "").strip().split(" ")[::2])
Related