strings like this are fine
chris test 1
these are not
chris test 1 %^&%(^)&)(&
basically it should just be letters numbers and spaces.
however my code is still validating strings with special characters.
def post(self, request, *args, **kwargs): data = ContentCreatorCreatorDisplayNameUniqueValidCheckSerializer(data=request.data) if data.is_valid(raise_exception=True): data = data.validated_data # check if the name is valid # only letters numbers and spaces pattern = re.compile('([a-zA-Z0-9s])+') print(data['name']) if pattern.match(data['name']): print('it validated the pattern')
the important regex lines being:
pattern = re.compile('([a-zA-Z0-9s])+') print(data['name']) if pattern.match(data['name']):
when I do a check on regExr.com
the code works against test input as shown in the image.
Is there something I am missing with python? Is my regex still off?
re.match method only makes sure that the match starts from the beginning of a given string. You still have to anchor the end of the string with a
$ to ensure the pattern covers the entire string:
pattern = re.compile('[a-zA-Z0-9s]+$')