Home > other >  Regex for a extracting a string starting with a particular word and ending with a year
Regex for a extracting a string starting with a particular word and ending with a year

Time:04-22

INPUT : The string is enclosed CASE NO.: Appeal (civil) 648 of 2007 in between.

OUTPUT : CASE NO.: Appeal (civil) 648 of 2007

I want to extract the string starting with the word CASE NO.(Case Insensitive) and ending with the first occurrence of a year.

I have tried the following code which works well with the starting part.

case_no = re.search(r"(?=Case No.)(\w \W ){5}", contents,re.IGNORECASE)
if case_no:
    print(case_no.group())

CodePudding user response:

I would use a lazy dot here to match the nearest year occurring after CASE NO.:

inp = "The string is enclosed CASE NO.: Appeal (civil) 648 of 2007 in between."
m = re.search(r'\bCASE NO\.:.*?\b\d{4}\b', inp)
print(m.group())  # CASE NO.: Appeal (civil) 648 of 2007
  • Related