So I need this for validating a part of a telephone number.
How can I check if [0-9]{5}
also includes at least once [1-9]
?
Positive:
12345
12340
12305
12045
10345
00001
00010
00100
01000
10000
10001
10011
10111
11111
Negative:
00000
123456
CodePudding user response:
You can do this:
^[0-9]*[1-9] [0-9]*$
Optionally starting (^[0-9]*
) and optionally ending ([0-9]*$
) with anything from 0-9, and somewhere in between at least one digit without zero [1-9]
Edit:
My answer was missing the length of the input. Thanks to CarySwoveland for helping out using lookarounds:
You can either use positive lookahead to make sure at least one non-zero digit is contained in the input:
^(?=.*[1-9])\d{5}$
Or invert it to negative lookahead to avoid the zero-only input:
^(?!00000)\d{5}$
However, changing the negative lookahead requires you to update the number of zeros and the digit count \d{n}
. This becomes harder the longer the input gets. Therefore, I would recommend using the positive lookahead.