代码之家  ›  专栏  ›  技术社区  ›  horcle_buzz

任意数目的带“;”的数字组的正则表达式以及分组之间的'\s'

  •  1
  • horcle_buzz  · 技术社区  · 6 年前

    我有下面的代码来根据下面列出的情况提取给定字符串中的第一组和最后一组数字。这是可行的,但似乎并不理想:

    import re
    
    # case 1
    pattern = '\d+\ \d+'
    string = 'Hello 999 888999'
    test = re.findall(pattern, string, flags=0)[0].split()
    print('{0}, {1}'.format(test[0], test[len(test)-1]))
    
    # case 2
    pattern = '\d+\ \d+;\d+ \d+'
    string = 'How are things 999 888999;222 444'
    test = re.findall(pattern, string, flags=0)[0].split()
    print('{0}, {1}'.format(test[0], test[len(test)-1]))
    
    # case 3
    pattern = '\d+\ \d+;\d+ \d+;\d+ \d+'
    string = 'It is nice 999 888999;222 444;33 55'
    test = re.findall(pattern, string, flags=0)[0].split()
    print('{0}, {1}'.format(test[0], test[len(test)-1]))
    
    # case 4
    pattern = '\d+\ \d+;\d+ \d+;\d+ \d+;\d+ \d+'
    string = 'Please help yourself 999 888999;222 444;33 55;44 6661'
    test = re.findall(pattern, string, flags=0)[0].split()
    print('{0}, {1}'.format(test[0], test[len(test)-1]))
    

    1. 任意字数后跟数字后跟空格后跟数字
    2. 任意字数,后跟数字,后跟空格,后跟以“;”分隔的数字后跟空格,后跟以“;”分隔的数字后跟空格和数字
    3. 等。

    对如何一下子做到这一点有什么建议吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   CertainPerformance    6 年前

    听起来常见的模式是,你想找到最初的数字串,最后的数字串。你可以用

    (\d+).*?(\d+$)
    

    要尽快匹配和捕获尽可能多的数字,请懒洋洋地重复任何字符,直到找到另一个数字字符串,后跟该字符串的结尾。

    pattern = re.compile(r'(\d+).*?(\d+$)')
    for str in ['Hello 999 888999', 'How are things 999 888999;222 444', 'It is nice 999 888999;222 444;33 55', 'Please help yourself 999 888999;222 444;33 55;44 6661']:
        match = re.search(pattern, str)
        print(', '.join(match.groups()))
    

    https://regex101.com/r/FgVIdV/1

        2
  •  0
  •   Dani Mesejo    6 年前

    你可以试试这个:

    import re
    
    pattern = re.compile('(\d+\s\d+(;)?){1,4}')
    
    texts = ['Hello 999 888999', 'How are things 999 888999;222 444', 'It is nice 999 888999;222 444;33 55',
             'Please help yourself 999 888999;222 444;33 55;44 6661']
    
    for text in texts:
        match = pattern.search(text)
        if match:
            split = match.group().split()
            print('{0}, {1}'.format(split[0], split[len(split) - 1]))
    

    输出

    999, 888999
    999, 444
    999, 55
    999, 6661
    

    (\d+\s\d+(;)?){1,4} 1、2、3或4次。模式和你的差不多:

    • \d+ 一个或多个数字
    • \s 一个空格
    • \d级+ 一个或多个数字
    • 然后是可选的 ; ( (;)? )