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

通过正则表达式查找符号之间的值,其中符号可能是值的一部分

  •  0
  • BernardL  · 技术社区  · 7 年前

    有一个字符串,我正试图从符号之间提取值,但符号或分隔符也恰好是字符串的一部分。

    假设以下字符串:

    message =': :1:1st message:2a:2nd message:x:this is where it fails status: fail :3:3rd message'
    

    以及预期结果:

    ['1st message','2nd message','this is where it fails status: fail','3rd message']
    

    当前代码和结果:

    import re
    def trans(text):
        text = text+':'
        tag = re.findall(r':(.*?):',text)
        return [i for i in tag if not i.isspace()]
    
    trans(message)
    
    >>['1st message', '2nd message', 'this is where it fails status', '3']
    

    你知道我怎样形成正则表达式来包含要包含的模式吗 'status: fail ' 作为结果的一部分?

    3 回复  |  直到 7 年前
        1
  •  2
  •   David Ferenczy Rogožan Hugo L.M    7 年前

    尝试使用 negative lookahead : r'[^\s]:(.*?):(?!\s)

    结果:

    ['1st message',
     '2nd message',
     'this is where it fails status: fail ',
     '3rd message']
    
    • [^\s] 与前面有空格字符的冒号不匹配,以便修复 3rd message
    • :(?!\s) 是为了匹配 冒号后面没有空格字符 status: fail .
        2
  •  1
  •   CertainPerformance    7 年前

    你可以用

    re.findall(r'(?<=:\S:).+?(?=\s*:.:|$)', message)
    

    在冒号(或字符串的开头)中查找一个字符,然后匹配并延迟重复任何字符,直到lookahead看到冒号(或字符串的结尾)中的另一个字符。

    ['1st message', '2nd message', 'this is where it fails status: fail', '3rd message']
    
        3
  •  0
  •   Matt.G    7 年前

    :\d+:\K.*?(?=:\d+|$)

    Demo