[英]Python regex accept all characters except <>%;$
我想允许除<>%;$
之外的任何字符
我所做的是r'^[^<>%;$]'
但它似乎无法正常工作。
r'^[^<>%;$]+$'
你错过了量词* or +
。
r'^[^<>%;$]'
正则表达式只检查<
, >
, %
,;之外的字符;
, $
在字符串的开头因为^
anchor(断言字符串开头的位置)。
您可以使用Python 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演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.