import re
s = '18year old 23 year old 99 years old but not 25-year-old and 91year old cousin is 99 now and 90-year-old or 102 year old'从中s,我想使用正则表达式提取所有 90 岁或以上的年龄。例如,99 years old将被提取但不是18year old.我试过以下 reg = r'(9\d|\d{3,})(-year-old)|(9\d|\d{3,})( year old)'
r1 = re.findall(reg,s)
r1这给了我[('90', '-year-old', '', ''), ('', '', '102', ' year old')]理想情况下,我想要这个输出['99 years old', '91year old', '90-year-old', '102 year old' ]如何更改我的正则表达式reg以获得我想要的输出?
1 回答
皈依舞
TA贡献1851条经验 获得超3个赞
这个正则表达式会做你想做的事:
(?:9\d|1\d{2})(?:\s|-)?years?(?:\s|-)?old
正则表达式演示
解释:
(?:9\d|1\d{2}) # Non-capturing group - match 9x or 1xx
(?:\s|-)? # Non-capturing group - optionally match whitespace or -
years? # Match year and optionally s
(?:\s|-)? # Non-capturing group - optionally match whitespace or -
old # Match old
代码片段:
reg = r'(?:9\d|1\d{2})(?:\s|-)?years?(?:\s|-)?old'
r1 = re.findall(reg,s)
print(r1)
# ['99 years old', '91year old', '90-year-old', '102 year old']
添加回答
举报
0/150
提交
取消