Home > Software design >  How to find a date at a specific word using regex
How to find a date at a specific word using regex

Time:10-08

Sentence : "I went to hospital and admitted. Date of admission: 12/08/2019 and surgery of Date of surgery: 15/09/2015. Date of admission: 12/05/2018 is admitted Raju"

keyword: "Date of admission:"

Required solution: 12/08/2019,12/05/2018

Is there any solution to get the dates near "Date of admission:" only. Is there any solution

CodePudding user response:

I was unable to reproduce the result in the answer by @Ders. Plus I think .findall() is more appropriate here anyway, so:

import re

pattern = re.compile(r"Date of admission: (\d{2}/\d{2}/\d{4})")

print(pattern.findall(s))
# ['12/08/2019', '12/05/2018']

CodePudding user response:

Use a capturing group. If the re matches, then you can get the contents of the group.

import re

p = re.compile("Date of admission: (\d{2}/\d{2}/\d{4})")
dates = p.findall(sentence)
# ["12/08/2019", "12/05/2018"]
  • Related