Fa Thur
Fa Thur

Reputation: 5

How to validate string using regex

I want to validate an 8 character string with the following position-wise character constraints:

  1. The first position must be one of these letters: A/M/P/B/S
  2. Second and third position are letters from AA to ZZ
  3. Fourth position contains a number between 1 - 4
  4. Fifth position contains a number between 1 - 4
  5. Sixth - eighth position must be a number 000 - 999

If it doesn't match, it will return FALSE. Here is my code:

import re                       

text = input("input:")
print(text)
   check = re.search("[^S|B|M|P|A][AA-ZZ][1-4][1-4][000-999]", text)
if check: 
 print("TRUE")
else: 
 print("FALSE")

Ex : AIK22001 The Uotput should be 'True'

Here, I have tried using regex Python library, but the output was wrong. It returns False whether it is expected to be True.

Upvotes: 0

Views: 1571

Answers (1)

Joe Hildebrand
Joe Hildebrand

Reputation: 10414

Here's an example of how to use the regex101 site that Akshay Sehgal mentioned above:

https://regex101.com/r/KtzJY6/1

You'll see the regex there is ^[AMPBS][A-Z]{2}[1-4]{2}[0-9]{3}$. Important features to note here:

  • The anchors ^ and $ attach to the beginning and ending of the string, which prevents inputs that are too short and too long from matching.
  • Quantifiers like {2}, which means "two of the previous things"
  • Notice how square brackets [] work. You don't need | in the middle of them, and ranges only work on single characters; [AA-ZZ] matches 'A', anything between 'A' and 'Z', and 'Z', which is probably not what you wanted.

Upvotes: 1

Related Questions