3

I want to allow any character except <>%;$

What I have done is r'^[^<>%;$]' but it seems not working.

1
  • Please post relevant code. Even better put a running example on ideone.com or codepad.org and share the link here. Commented Feb 24, 2016 at 9:23

2 Answers 2

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

You missed the quantifier * or +.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.