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

时间:2016-02-24 09:22:15

标签: python regex

我想允许除<>%;$

之外的任何字符

我所做的是r'^[^<>%;$]',但似乎无效。

2 个答案:

答案 0 :(得分:3)

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

您错过了量词* or +

答案 1 :(得分: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 demo