Re.match总是在python中返回None

时间:2013-06-12 06:42:37

标签: python regex python-3.x

我正在尝试进行一个非常简单的正则表达式匹配(除了'['和']'之外的所有可打印的anscii字符的否定)。 When I tested my pattern in regex pal我得到了我想要的匹配。然后我转到我的python单元测试,我的匹配永远不会返回true

def testChatChars(string):
   return re.match('[^\x20-\x5A\x5C\x5E-\x7E]', string) is not None

print("testing Chat validation") 
print(testChatChars("") == False)
print(testChatChars("this is a valid chat message") == True)
print(testChatChars("9999abcdefghijklmnopqrxtuvxyz ABCDEFGHIJKLMNOP!@#$(^&*(&%$^^)*)!{},.;'\|?/7") == True )
print(testChatChars("this is not [ valid chat message") == False)
print(testChatChars("this is not ] valid chat message") == False)
print(testChatChars("9999abcdefghijklmnopqrxtuvxyz [][][[][]ABCDEFGHIJKLMNOP!@#$(^&*(&%$^^)*)!{}[],.;'\|?/7ونِكود碼標準萬國") == False)

返回

False //should be true
False //should be true
False //should be true
True
True
True

re.match因某种原因总是返回。

更新: tried to change my code in the suggested fashion 新产出

False
False
True
False
False
False

1 个答案:

答案 0 :(得分:1)

def testChatChars(string):
   return re.match(r'[\x20-\x5A\x5C\x5E-\x7E]+$', string) is not None