Guys I have these two REGEX but I couldn't join them.
I need it not to have a leading zero and contain from 1 to 4 or 9 characters.
Accept:
1
12
10
123
103
1234
1004
123456789
456004500
Not:
01 (leading zero)
003 (leading zero)
0234 (leading zero)
12345 (5 characters)
1234567891 (10 characters)
^(?!0{1})[0-9]{9}$
^([0-9]{1}|[0-9]{2}||[0-9]{3}||[0-9]{4}|[0-9]{9})$
CodePudding user response:
Use [1-9] to match the first character. Then match the remainder the appropriate number of times to get 1-4 or 9 total digits.
^[1-9]([0-9]{0,3}|[0-9]{8})$
CodePudding user response:
Use
^(?!0)(?:\d{1,4}|\d{9})$
See regex proof.
EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
0 '0'
--------------------------------------------------------------------------------
) end of look-ahead
--------------------------------------------------------------------------------
(?: group, but do not capture:
--------------------------------------------------------------------------------
\d{1,4} digits (0-9) (between 1 and 4 times
(matching the most amount possible))
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\d{9} digits (0-9) (9 times)
--------------------------------------------------------------------------------
) end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
