Home > other >  Python allowing @ in alphanumeric regex
Python allowing @ in alphanumeric regex

Time:12-22

I only want to allow alphanumeric & a few characters ( , -, _, whitespace) in my string. But python seems to allow @ and . (dot) along with these. How do I exclude @?

import re

def isInvalid(name):
    is_valid_char = bool(re.match('[a-zA-Z0-9 -_\s] $', name))
    if not is_valid_char:
        print('Name has invalid characters')
    else:
        print('Name is valid')
        
isInvalid('abc @')    

This outputs 'Name is valid', how do I exclude @? Have tried to search this, but couldn't find any use case related to @. You can try this snippet here - https://www.programiz.com/python-programming/online-compiler/

CodePudding user response:

This part -_ of your regex matches in range of index 43 and 95. You need to use a \ to remove the meaning of the -

Your RegEx should look like this: [a-zA-Z0-9 \-_\s] $

CodePudding user response:

Judging from the regex you've used in your code, I believe you're trying to allow all alphanumeric characters and the characters , -, _ and empty spaces in your string. In that case, the problem here is that you're not escaping the characters and -. These characters are special characters in a regular expression and need to be escaped. (what characters need to be escaped depends on what flavor of regex you're working with, more info here).

Modifying your code as follows produces expected results:

import re

def isInvalid(name):
    is_valid_char = bool(re.match('[a-zA-Z0-9\ \-_\s] $', name))
    if not is_valid_char:
        print('Name has invalid characters')
    else:
        print('Name is valid')
        
isInvalid('abc @')  # prints "Name has valid characters"

You can run it online here

  • Related