简体   繁体   中英

Re.match always returning None in python

I'm trying to make a very simple regex match ( the negation of all printable anscii characters other then '[' and ']'). When I tested my pattern in regex pal I got the matching that I wanted. Then I moved to my python unit test and my match never returns 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)

Which is returning

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

re.match is always returning none for some reason.

UPDATE: tried to change my code in the suggested fashion new output is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM