skip to Main Content

I have difficulty with regular expression.

Regular expression requirements: from 3 to 20 characters, Latin, may contain numbers, but not consist of them, without spaces, without special characters (hyphens and underscores are allowed).

At the moment, my expression looks like this:

const regexp = /^(?=.*[A-Za-z]{1,}[0-9]{0,}).{3,20}$/;

I will be grateful for any help

UPDATE

"May contain numbers, but not consist of them" means at least one letter.

2

Answers


  1. you can use a negative lookahead for excluding strings with spaces

    (?!.*s)
    
    /^(?=.*[A-Za-z]{1,}[0-9]{0,})(?!.*s).{3,20}$/
    
    Login or Signup to reply.
  2. What is wrong with the regular expression? I expect someone will just write an answer for you, but you should post a list of strings that are accepted and should be, that are accepted and should not be, are not accepted and should be, and that are not accepted and shouldn’t be. /^[w-]{3,20}$/m should catch all cases you described except "not-numbers-only". If it cannot contain only numbers I would check that after the fact (two simple regexes may be faster than a complicated one). Can it start with a hyphen? Adding a list of acceptable and non-acceptable strings, and using https://regex101.com/ are your friend.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search