Search code examples
regexdigit

Regular expression : validate numbers greater than 0, with or without leading zeros


I need a regular expression that will match strings like T001, T1, T012, T150 ---- T999.

I made it like this : [tT][0-9]?[0-9]?[0-9], but obviously it will also match T0, T00 and T000, which I don't want to.

How can I force the last character to be 1 if the previous one or two are zeros ?


Solution

  • Quite easy using a negative lookahead: ^[tT](?!0{1,3}$)[0-9]{1,3}$

    Explanation

    ^               # match begin of string
    [tT]            # match t or T
    (?!             # negative lookahead, check if there is no ...
        0{1,3}      # match 0, 00 or 000
        $           # match end of string
    )               # end of lookahead
    [0-9]{1,3}      # match a digit one or three times
    $               # match end of string
    

    Online demo