我想要以下測驗用例的正則運算式,以便獲得正確的輸出:-
測驗用例:
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
我已經嘗試過了1re.findall(r'aged about(?:\:)? (?P<age>\d ) ', txt),但不適用于所有文本案例。如果您找到任何內容,請告訴我
uj5u.com熱心網友回復:
嘗試(txt是您的問題文本)(正則運算式演示。):
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)
印刷:
56
46
37
56
61
63
9
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528897.html
標籤:Python正则表达式
