1

我正在尝试进行一个非常简单的正则表达式匹配(否定除'['和']'之外的所有可打印的anscii字符)。当我在 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 总是不返回任何内容。

更新: 尝试以建议的方式更改我的代码 新输出是

False
False
True
False
False
False
4

1 回答 1

2
def testChatChars(string):
   return re.match(r'[\x20-\x5A\x5C\x5E-\x7E]+$', string) is not None
于 2013-06-12T07:08:32.617 回答