Skip to main content
 首页 » 编程设计

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

2024年11月24日34Leo_wl

我根据收到的有关此问题的答案编辑了以下正则表达式。

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

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

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

请您参考如下方法:

你可以使用

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

参见 regex demo输出 ['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 或 month
  • 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 .