As great as the answer is, it might not be very easy for a new bee
This does exactly the same thing
^([a-z]{2,}|[a-z][0-9]{2,})[0-9]*$
This way ^
signifies the beginning position of the string,it signifies the beginning of the string
The ()
is used to define a group and the group defined in this case is all lowercase alphabets with a minimum lenght of 2, because the {}
is used to specify the length of the string
Then the pipe symbol used there |
signifies "or" then the next expression is [a-z][0-9]{2,}
which means all lowercase alphabets followed by an integer whose minimum length should be 2.
Finally after that group they can have zero or more occurance of an integer this is enforced using the *
symbol and $
denotes the end of the string
So this regex reads thus: from the begining of the string,it should begin with lowercase alphabets with a minimum length of 2 or a lowercase alphabet and a number but the numbers length can't be less than 2 then you can have a series of integers or numbers come after them or you can have none
This is a very direct and constrained solution and probably should be used for learning purposes or in cases that it's just required as so, in real life applications there may be need for more flexible regular expressions
More breakdown:
^([a-z]{2,}|[a-z][0-9]{2,})[0-9]*$
'^` asserts position at start of a line
1st Capturing Group ([a-z]{2,}|[a-z][0-9]{2,})
1st Alternative [a-z]{2,}
Match a single character present in the list below
[a-z]{2,}
{2,}
Quantifier — Matches between 2 and unlimited times, as many times as possible, giving back as needed (greedy)
a-z
a single character in the range between 'a' (index 97) and 'z' (index 122) (case sensitive)
2nd Alternative [a-z][0-9]{2,}
Match a single character present in the list below [a-z]
a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
Match a single character present in the list below [0-9]{2,}
{2,}
Quantifier — Matches between 2 and unlimited times, as many times as possible, giving back as needed (greedy)
0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
Match a single character present in the list below [0-9]*
*
Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
0-9
a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
$
asserts position at the end of a line
Demo
import re
pattern="^([a-z]{2,}|[a-z][0-9]{2,})[0-9]*$"
if re.match(pattern,input()):
print("Ok")
else:
print("Not ok")