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)-year或months?- 一个可选的s\b- 字边界。
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'
请参阅此正则表达式演示。
添加回答
举报
