为了账号安全,请及时绑定邮箱和手机立即绑定

检测一个字符串中的多个模式 - python-regex

检测一个字符串中的多个模式 - python-regex

Smart猫小萌 2021-11-16 15:35:13
根据我在这个问题上收到的答案,我编辑了以下正则表达式。我的字符串混合了年和月的术语。我需要用正则表达式检测两者。String1 = " I have total exp of 10-11 years. This includes 15yearsin SAS and 5 years in python. I also have 8 months of exp in R programming."import repat= re.compile(r'\d{1,3}(?:\W+\d{1,3})?\W+(?:plus\s*)?(?:year|month|Year|Month)s?\b', re.X)experience = re.findall(pat,String1 )    print(experience)['10-11 years', '5 years', '8 months']但我也想要没有空格的条款,即 15 年(因为我正在阅读自由流动的文本)。任何人都可以帮助实现正确的正则表达式吗?
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您可以使用

r'\b\d{1,2}(?:\D+\d{1,2})?\D+(?:year|month)s?\b'

正则表达式演示输出['10-11 years', '15 years in SAS and 5 years', '8 months']

细节

  • \b - 字边界

  • \d{1,2} - 一位或两位数字

  • (?:\D+\d{1,2})? - 一个可选的序列

    • \D+ - 1+ 个数字以外的字符

    • \d{1,2} - 1 或 2 位数字

  • \D+ - 一个或多个非数字字符

  • (?:year|month)-yearmonth

  • s? - 一个可选的 s

  • \b - 字边界。

Python 演示

import re

String1 = " I have total exp of 10-11 years. This includes 15 years in SAS and 5 years in python. I also have 8 months of exp in R programming."

reg = r'\b\d{1,2}(?:\D+\d{1,2})?\D+(?:year|month)s?\b'

print(re.findall(reg, String1))

# => ['10-11 years', '15 years in SAS and 5 years', '8 months']

注意:如果您打算['10-11 years', '15 years', '5 years', '8 months']替换\D+为\W+(一个或多个字母、数字、下划线以外的字符)并使用


r'\b\d{1,2}(?:\W+\d{1,2})?\W+(?:year|month)s?\b'

请参阅此正则表达式演示


查看完整回答
反对 回复 2021-11-16
  • 1 回答
  • 0 关注
  • 212 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号