Validate with regular expression python

-1

I'm working with python and I'm doing a chat, I need to validate that if the user sends a code as follows:

Code 1: ZH150000001

Code 2: ZHS150000001

Validate if it starts with ZH or ZHS and what follows is a number.

I think that it could be with a regular expression but I'm not sure.

If so, do you know of any? or from an understandable regular expression generator?.

I appreciate your help.

    
asked by Jhonatan Rodriguez 09.03.2018 в 16:54
source

2 answers

3

You're right, a regular expression would validate this. For example, the following regular expression validates what you are saying

^ZHS?\d+$

I'll explain everything to you

  • ^ZH This forces the text to start (this is marked with ^ ) with ZH
  • S? This indicates that the letter S is optional (may or may not come)
  • \d+ means any digit, repeated 1 or more times (we have not set a limit)
  • $ indicates that it is the end of the text read, you should not continue with more text behind.

A quick example to test such regular expression in python would be:

re.match(r'^ZHS?\d+$', 'ZH150000001')

I forgot to comment, if this returns None , is that there has not been a match, if you return a reference, it is that if you have found it

    
answered by 09.03.2018 / 17:01
source
1

The regular expression you're looking for is (ZHS?\d+) . I explain it to you in parts:

Parentheses delimit a segment to search. They are not strictly necessary but if they do not put them "match" they will not return what they find.

The letters are what they are, Z , then H and then S . The S is followed by an interrogation that means "0 or 1".

Then comes \d , which means "digit", that is, from 0 to 9. The% sign + that goes behind indicates that there must be a series of 1 or more.

On this page you can try your regular expressions in Python: link

    
answered by 09.03.2018 в 17:03