Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading