1

I want regex for the following test cases so that i can get the proper output:-

Test Cases:

Input:

address = "73/75 agedabout 56 years, residing at j,j 59 moil"

Output:
60

address = "12th street t.vial age 46yrs, residing at D.NO 59
Eswaran Koil St"

Output:
46

address = "Room no 43 R.Kesavan aged about 37 years, residing at
D.NO 59 Eswaran Koil St"

Output:
37

address = "Door no 32 R.Kesavan 56yrs, residing at D.NO 59 Eswaran
Koil St"

Output:
56

address = "12-4-67 , R.Kesavan aged about 61, residing at D.NO 59
Eswaran Koil St"

Output:
61

address = "R.Kesavan age63, residing at D.NO 59 Eswaran Koil St"

Output:
63

address = "R.Kesavan aged 9, residing at D.NO 59 Eswaran Koil St"

Output:
9

I have tried this 1re.findall(r'aged about(?:\:)? (?P<age>\d+) ', txt), but not working for all text cases.Let me know if u find any

5
  • The first input has agedabout instead of aged about; is that a typo on your part or a variant that needs to be anticipated? Commented Nov 7, 2022 at 18:02
  • Based on the test inputs, I think the best approach would be to look for the numerical string that appears after "age" but before "at". Commented Nov 7, 2022 at 18:04
  • @BenGrossmann its a variant that needs to be anticipated Commented Nov 7, 2022 at 18:05
  • @BenGrossmann for some cases there is no age word also..whatever i am trying is ending up failing one of the test casses Commented Nov 7, 2022 at 18:07
  • That's true... I suppose that you could account for those cases by looking for the last number that appears before "yr" or "year" in the event that age is not present in the string. Commented Nov 7, 2022 at 18:09

1 Answer 1

2

Try (txt is your text from the question) (regex demo.):

import re

pat = re.compile(r"(\d+)\s*ye?a?rs?|aged?\D*(\d+)")

for a, b in pat.findall(txt):
    age = b if a == "" else a
    print(age)

Prints:

56
46
37
56
61
63
9
Sign up to request clarification or add additional context in comments.

2 Comments

ye?a?rs? is a neat trick! Nice answer.
That ye?a?rs? was great , thankyou

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.