Find using regex a substring exist , if yes segregate if from the main string in python

Viewed 65

i have a string as below

strng ="Fiscal Year Ended March 31, 2018 Total Year (in $000's)"

if the above string has a year substring (e.g.. 2014,2015 etc), separate out the 'year' substring and the rest.

for getting the 'year' i am using

re.findall(r"\b20[012]\d\b",strng)

how can i get the rest of the substring also. expected output is

year_substring --> '2018'
rest --> 'Fiscal Year Ended March 31, Total Year (in $000's)'

is there any way to get both using regex?

1 Answers

You may capture the 3 parts, string before year, year and the rest and then concat Group 1 and 3 to get the rest:

import re
strng ="Fiscal Year Ended March 31, 2018 Total Year (in $000's)"
m = re.search(r"(.*)\b(20[012]\d)\b(.*)",strng)
if m:
    print("YEAR: {}".format(m.group(2)))
    print("REST: {}{}".format(m.group(1),m.group(3)))

See the Python demo. Output:

YEAR: 2018
REST: Fiscal Year Ended March 31,  Total Year (in $000's)

If your string has multiple matches use re.split with your pattern:

import re
strng ="Fiscal Year Ended March 31, 2018 Total Year (in $000's) and Another Fiscal Year Ended May 31, 2019 Total Year (in $000's)"
print(re.findall(r"\b20[012]\d\b",strng))
# => ['2018', '2019']
print(" ".join(re.split(r"\b20[012]\d\b",strng)))
# => Fiscal Year Ended March 31,   Total Year (in $000's) and Another Fiscal Year Ended May 31,   Total Year (in $000's)

See another Python demo.

You may strip the groups from leading/trailing whitespace with strip(), too.

Related