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:

  1. allow a-z a-z
  2. allow 0-9
  3. allow - , . characters
  4. allow spaces (\s)
  5. do not allow more 2 digits
  6. 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:

  1. test 12 test
  2. test12
  3. 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

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -