首页 文章

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

提问于
浏览
1

如何编写在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()

3 回答

  • 3

    如果您想匹配您的值而不需要捕获组,您可以使用:

    \b(?:\d+-\d+ [yY]ears|[02-9] [Yy]ears|1 [Yy]ear|[1-9]\d+\+? [Yy]ears)\b

    regex demo

    Explanation

    • \b 字边界

    • (?: 非捕获组

    • \d+-\d+ [yY]ears 匹配格式10 - 15年

    • |

    • [02-9] [Yy]ears 匹配格式0或2 - 9年

    • |

    • 1 [Yy]ear 匹配格式1年

    • |

    • [1-9]\d+\+? [Yy]ears 匹配格式10年

    • ) 关闭非捕获组

    • \b 字边界

    Python demo

  • 2

    ([\ d - ])\ s(年?)


    import re
    
    x ="""
    123 10+ years some text
    some text 99 10 years ssss
    text 1 year and more text
    some text 10-15 years some text
    """
    
    result = re.findall(r"([\d+-]+)\s+(years?)", x, re.IGNORECASE)
    print(result)
    

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

    Python Demo

    Regex Demo


    正则表达式说明:

  • 2

    你可以用

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

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

    Details

    • (\d+(?:-\d+)?\+?) - 第1组:

    • \d+ - 1位数

    • (?:-\d+)? - 与 - 匹配的可选组,然后是1位数

    • \+? - 一个可选的 + 字符

    • \s* - 0个空格

    • (years?) - 第2组: yearyears

    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')
    

相关问题