Only allow 2 digits in a string using regex -
i need regex allows maximum of 2 digits (or whatever desired limit actually) entered input field.
the requirements field follows:
- allow
a-z
a-z
- allow
0-9
- allow
-
,.
characters - allow spaces (
\s
) - do not allow more 2 digits
- do not allow other special characters
i have managed put following regex
based on several answers on so:
^(?:([a-za-z\d\s\.\-])(?!([a-za-z]*\d.*){3}))*$
the above regex
close. works following:
- test 12 test
- test12
- test-test.12
but allows input of:
123
(but not 1234
, it's close).
it needs allow input of 12
when only digits entered field.
i in finding more efficient , cleaner (if possible) solution current regex
- must still regex
, no js
.
you may use negative lookahead anchored @ start make match fail once there 3 digits found anywhere in string:
^(?!(?:[^0-9]*[0-9]){3})[a-za-z0-9\s.-]*$ ^^^^^^^^^^^^^^^^^^^^^^^
see regex demo
details:
^
- start of string(?!(?:[^0-9]*[0-9]){3})
- negative lookahead failing match if 3 following sequences found:[^0-9]*
- 0 or more chars other digits[0-9]
- digit (thus, digits not have adjoining)
[a-za-z0-9\s.-]*
- 0+ ascii letters, digits, whitespace,.
or-
symbols$
- end of string.
Comments
Post a Comment