Cyan Cyan - 4 months ago 19
Java Question

Regular expression - between 1 to four digits, at least one non zero

I am looking for a regular expression to verify if a number between 1 to 4 digits that has at least one non zero digit.

Example:

0 -false
1 -true
000 -false
100 -true
1111-true
0000-false


Thanks.

Answer

You can use this look ahead based regex:

^(?!0+$)[0-9]{1,4}$

RegEx Demo

(?!0+$) is negative look ahead to assert all digits are not zeroes.