Python allowing @ in alphanumeric regex

Question:

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/

Asked By: Optimus Prime

||

Answers:

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]+$

Answered By: Fabian

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

Answered By: Daksh Goyal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.