我希望允许任何字符,除了
我所做的是
<>%;$
。我所做的是
r'^[^<>%;$]'
,但似乎不起作用。r'^[^<>%;$]+$'
你漏掉了量词*
或+
。
r'^[^<>%;$]'
只检查字符串开头的除了<
, >
, %
, ;
, $
之外的字符,因为使用了锚点^
(断言字符串开头)。re.search
函数和字符类[<>%;$]
来检查一个字符串是否包含这些字符,或者你可以定义一个这些字符的set
并使用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
请查看IDEONE演示