如果您正在测试字符串匹配,您应该比较字符串并且使用 re.search 就足够了:
output = "your test contains errors"
match2 = re.search('(.* contains errors)',output)
mat2 = 'your test contains errors'
if match2 and match.group() == mat2:
print "PASS"
findall 也会返回多个匹配项,因此如果有多个匹配项,即使使用 mat2 = ['your test contains errors'] 也会失败。
您的正则表达式方法实际上没有意义,如果您要比较两个字符串是否基于 在上面的 python 程序中,我在“match2”和 mat2 中有字符串。如果相同,它应该打印 PASS。 你是,那么你根本不应该使用正则表达式:
output = "your test contains errors"
mat2 = 'your test contains errors'
if output == mat2:
print "PASS"
你的正则表达式相当于str.startswith,所以很简单:
if output.startswith(mat2):
print "PASS"
也会这样做。
您的正则表达式方法将匹配子字符串:
import re
output = "foo your test contains errors"
match2 = re.findall('(.* contains errors)',output)
print(match2)
输出:
['foo your test contains errors']
因此,使用正则表达式获得匹配的唯一方法是字符串以 your test ... 开头,str.startswith 可以在不需要正则表达式的情况下进行测试。
因此,如果您想查找字符串是否以'your test contains errors' 开头,请使用str.startswith,如果您只想查找contains errors 是否在字符串中,请使用if "contains errors" in output 或等效使用if match2:,使用搜索作为这将查找"contains errors" 是否在您的字符串中,前面有任何字符。
您也可以使用if 'your test contains errors' 来查找子字符串是否在字符串中的任何位置,但这不是您的正则表达式正在做的事情。