Python正则表达式接受除了<>%;$之外的所有字符。

3
我希望允许任何字符,除了<>%;$
我所做的是r'^[^<>%;$]',但似乎不起作用。

请发布相关代码。更好的是,在 ideone.com 或 codepad.org 上放置一个运行示例,并在此处共享链接。 - DhruvPathak
2个回答

4
r'^[^<>%;$]+$'

你漏掉了量词*+


0
正则表达式r'^[^<>%;$]'只检查字符串开头的除了<, >, %, ;, $之外的字符,因为使用了锚点^(断言字符串开头)。
你可以使用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演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接