I want to allow any character except <>%;$
What I have done is r'^[^<>%;$]' but it seems not working.
I want to allow any character except <>%;$
What I have done is r'^[^<>%;$]' but it seems not working.
The r'^[^<>%;$]' regex only checks for the characters other than <, >, %, ;, $ at the beginning of the string because of ^ anchor (asserting the position at the beginning of the string.
You can use Python re.search to check if a string contains any of these characters with a character class [<>%;$] or you can define a set of these characters and use any():
import re
r = re.compile(r'[<>%;$]') # Regex matching the specific characters
chars = set('<>%;$') # Define the set of chars to check for
def checkString(s):
if any((c in chars) for c in s): # If we found the characters in the string
return False # It is invalid, return FALSE
else: # Else
return True # It is valid, return TRUE
def checkString2(s):
if r.search(s): # If we found the "bad" symbols
return False # Return FALSE
else: # Else
return True # Return TRUE
s = 'My bad <string>'
print(checkString(s)) # => False
print(checkString2(s)) # => False
s = 'My good string'
print(checkString(s)) # => True
print(checkString2(s)) # => True
See IDEONE demo