Python Forum
Validate string using Regex - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Validate string using Regex (/thread-7701.html)



Validate string using Regex - rahul_raj1981 - Jan-21-2018

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!


RE: Validate string using Regex - Gribouillis - Jan-21-2018

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.



RE: Validate string using Regex - rahul_raj1981 - Jan-23-2018

Thanks Gribouillis