0

I have this code using regex as follows, but when all my characters are letters it gives out an output of "invalid" whereas it should not:

import re


def main():
    plate = input("Plate: ")
    if is_valid(plate):
        print("Valid")
    else:
        print("Invalid")


def is_valid(s):
    n = re.match(r"^[a-zA-Z]{2,5}[1-9][0-9]*$", s)
    if length(s) and n:
        return True

def length(s):
    if 2<=len(s)<=6:
        return True
    else:
        return False

main()

1 Answer 1

1

The problem here is that regex which I gave you will not match if the input is all letters. You would need to make the regex more complicated for that, I had given it to you assuming you were checking with s.isalpha() first to short circuit if all letters.

However this is a great question and allows us to use a more powerful regular expression to solve nearly the entire problem (except the total length which would be too advanced a regex to get into here, and i wouldnt recommend using it)

You can do this with two regular expressions or one with something called called 'alternation' in your regex to allow for either of two patterns to be matched.

  1. The easy way:
def is_valid(s):
    if not length(s):
        return False
    m = re.match(r"^[a-zA-Z]{2,6}$", s)
    #note n is exactly as you left it
    n = re.match(r"^[a-zA-Z]{2,5}[1-9][0-9]*$", s)
    return (m or n)

    #alternatively you can return (length(s) and (m or n))

The other option is alternation in the match for n but it pretty much is just combining the two so for readability i'd suggest not combining them here.

n = re.match(r"(^[a-zA-Z]{2,5}[1-9][0-9*$)|(^[a-zA-Z]{2,6}$)")

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .