NEB
NEB

Reputation: 734

Regular expression to validate a specific pattern

I'm trying to create a regular expression with the below restrictions

  1. Allow any character '\w\W\s' (e.g rand123#!#@adfads)
  2. Disallow only numbers (e.g 12312312)
  3. Disallow only non alphanumeric characters (e.g !@#$$#%#^%$^%)
  4. Number of characters must be between 3 to 60

Following along the lines of this answer, but could not get it work.

^(?=.{3,60}$)(?![\W_]*$)(?![0-9]*$)[\w\W\s]+$

Upvotes: 1

Views: 81

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

Note that \W matches \s, so '\w\W\s' can be reduced to [\w\W].

You may use 2 negative lookaheads anchored at the start to impose two "disallow-only" conditions like this:

^(?![\W_]+$)(?![0-9]+$)[\w\W]{3,60}$

See the regex demo

Pattern details:

  • ^ - start of string
  • (?![\W_]+$) - the string cannot consist of non-alphanumeric chars
  • (?![0-9]+$) - the string cannot consist of digits only
  • [\w\W]{3,60} - 3 to 60 any characters
  • $ - end of string.

Upvotes: 1

Related Questions