Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python allowing @ in alphanumeric regex

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/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading