如何构建适用于多种情况的正则表达式

how to construct a regex that works for multiple cases

我有以下代码匹配注释变量中的字符串,我如何构造匹配下面显示的两个注释的字符串?我想检查 QSPR TEST RESULTS:\siggy.* 和 TEST RESULTS: .*

import re    
comments = "QSPR TEST RESULTS:\siggy\QSPRLog\QCA\CST16\TestCaseLogs\N12345678-3_28_16_16_36_29_000_635947797916487681.html are the results"
#comments = "TEST RESULTS:BT ON\OFF LOOKS GOOD"

def matchcomments(comments, matchstring):
  matchobj = re.search(matchstring, str(comments))
  if matchobj:
    return True
  return False

def main ():
  try:
        string = r"QSPR TEST RESULTS:\siggy\.*"
        match = matchcomments(comments, string)
        if match == True:
          tested_bit_flag = True
        else:
          #string = r"Included in BIT"  
          string = r"DONOT MATCH"                                    
          match = matchcomments(comments, string)
          if match == True:
            tested_bit_flag = True
          else:
            tested_bit_flag = False                                         
  except KeyError:
        tested_bit_flag = False 
        print "This gerrit does not have comments:"
  print tested_bit_flag



if __name__ == "__main__":
  main()
string = r"(QSPR TEST RESULTS:\siggy\.*)|(DONOT MATCH)"

使用这个。

comments = "QSPR TEST RESULTS:\siggy\QSPRLog\QCA\CST16\TestCaseLogs\N12345678-3_28_16_16_36_29_000_635947797916487681.html are the results"
string = r"(?:QSPR)?\s?TEST\sRESULTS:\siggy\(.*)|(?:DONOT MATCH)"
matchobj = re.search(string, comments)
if matchobj:
    print True
    print matchobj.group(1) #Gives you the text you are interested in eg. QSPRLog\QCA\CST16\TestCaseLogs\N12345678-3_28_16_16_36_29_000_635947797916487681.html are the results
else:
    print False

解释:

(?:QSPR)?(?:DONOT MATCH)

(?:) 表示非捕获组。这个想法是检查组的存在或不存在(在本例中为 QSPR 或 DONOT MATCH)而不关心匹配是什么(因为我们已经知道它是什么)。末尾的问号表示该组是可选的。

\s?TEST\sRESULTS:\siggy\

这部分与给定的文本非常匹配。

(.*)

在群组中捕捉您感兴趣的文字。请注意,这是唯一的(捕获)组,因此当您使用参数 1 调用匹配对象的组属性时,您将获得您感兴趣的文本。

另请注意,此正则表达式将捕获 0 个或更多字符。替换为(.+),捕获1个或多个字符,保证非空。

|字符表示左边的表达式或右边的表达式应该匹配。在这种特殊情况下,由于右侧的表达式 (?:DONOT MATCH) 中没有组,因此在 comments="DONOT MATCH" 时调用 matchobj.group(1) 将 return None.确保稍后在代码中检查这一点。

如果我理解正确的话:

^(?:QSPR )?TEST RESULTS:.+$

这应该与您感兴趣的文字相匹配。

Demo here