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

detect multiple patterns in one string - 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']

但我也想要没有 space 的条款,即 15 年(因为我正在阅读自由流动的文本)。

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

您可以使用

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']regex demo

详情

  • \b - 单词边界
  • \d{1,2} - 一位或两位数
  • (?:\D+\d{1,2})? - 一个可选的序列
    • \D+ - 除了数字以外的 1+ 个字符
    • \d{1,2} - 1 或 2 位数
  • \D+ - 一个或多个非数字字符
  • (?:year|month) - 一个 yearmonth
  • s? - 一个可选的 s
  • \b - 单词边界。

Python demo:

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'

参见 this regex demo