regex in python to extract number

Question:

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

Asked By: mka

||

Answers:

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
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.