Python Forum

Full Version: Validate string using Regex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi,

I want to validate that the below string should only contain 0-9A-Za-z. Not sure how the space can be ignored and through the invalid message if it contains -

Please help
import re
inp1="input should only contain a to z 1 to 9 A to Z-"
if not re.search('[0-9A-Za-z]',inp1):
    print "input invalid"
else:
    print "input is valid"
Thanks in advance!
A way to ignore the space is simply to allow white space together with the characters you mentioned. I would use
valid = re.match(r'^(?:[a-zA-Z0-9]|\s)*$', inp1) is not None
Tips:
  1. Always use raw strings when you write regexes, ie r''
  2. Python 2 support ends in 2020, use python 3.
Thanks Gribouillis