Python Forum
Validate string using Regex
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Validate string using Regex
#1
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!
Reply
#2
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.
Reply
#3
Thanks Gribouillis
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Not able to validate data from a file Zving 7 3,641 Apr-20-2019, 05:16 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020