猿问

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

根据我在这个问题上收到的答案,我编辑了以下正则表达式。


我的字符串混合了年和月的术语。我需要用正则表达式检测两者。


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 re

pat= 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 年(因为我正在阅读自由流动的文本)。


任何人都可以帮助实现正确的正则表达式吗?


Smart猫小萌
浏览 213回答 1
1回答

森林海

您可以使用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)-year或months? - 一个可选的 s\b - 字边界。Python 演示:import reString1 = " 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'请参阅此正则表达式演示。
随时随地看视频慕课网APP

相关分类

Python
我要回答