Skip to main content
 首页 » 编程设计

python之在 Python 中使用正则表达式查找字符串中的多年经验

2025年05月04日14小虾米

我如何编写一个在 Python 中搜索以下内容的正则表达式:

10+ years 
10 years 
1 year 
10-15 years 

到目前为止,我已经使用了它,但它并没有为所有这些提供结果。

re_expression = '(\d+).(years|year|Year|Years)' 
    exp_temp = re.search(re_expression.decode('utf-8'),description) 
    experience_1='' 
    if exp_temp: 
        experience_1 = exp_temp.groups() 

请您参考如下方法:

你可以使用

r'(\d+(?:-\d+)?\+?)\s*(years?)' 

参见 regex demo .使用 re.I 标志编译以启用不区分大小写的匹配。

详情

  • (\d+(?:-\d+)?\+?) - 第 1 组:
    • \d+ - 1+ 位
    • (?:-\d+)? - 匹配 - 的可选组,然后是 1+ 位数字
    • \+? - 可选的 + 字符
  • \s* - 0+ 个空格
  • (years?) - 第 2 组:year 或 years

Python demo :

import re 
rx = re.compile(r"(\d+(?:-\d+)?\+?)\s*(years?)", re.I) 
strs = ["10+ years", "10 years", "1 year", "10-15 years"]  
for description in strs: 
    exp_temp = rx.search(description) 
    if exp_temp: 
        print(exp_temp.groups()) 

输出:

('10+', 'years') 
('10', 'years') 
('1', 'year') 
('10-15', 'years')