Home > Blockchain >  regex in python to extract number
regex in python to extract number

Time:11-08

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

CodePudding user response:

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
  • Related