Home > Software design >  Build a Regex with following conditions:
Build a Regex with following conditions:

Time:04-05

Need help with creating a regex with below conditions:

  1. Must contain at least 1 alphabet.
  2. Must contain at least 1 number.
  3. Any special character is optional.

This is the best i found in google and in other stackoverflow posts:

'^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*()])[a-zA-Z0-9] [@$!%*?&]*$'

But this does not solve my problem.

Am basically stuck at making the special character optional. The special character can come at start, middle or at the end of a string, basically at any position of a given and it may even be absent.

Any help is greatly appreciated.

CodePudding user response:

This should work for you:

'^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9@$!%*?&()]*$'

The tests at the beginning check for the mandatory characters, and then the square braces at the end should include all permitted symbols.

If you also want to allow square braces as special symbols too, put them at the beginning of the final character set:

'^(?=.*[a-zA-Z])(?=.*[0-9])[][a-zA-Z0-9@$!%*?&()]*$'

CodePudding user response:

You can use a single lookahead assertion using a negated character class [^a-z]*[a-z] to match a character a-z because .* will introduce unnecessary backtracking.

There is no benefit in asserting an optional character, you can just make the allowed characters part of the character class that does the matching.

Using a case insensitive match:

^(?=[^a-z]*[a-z])[a-z@$!%*?&]*\d[a-z\d@$!%*?&]*$
  • ^ Start of string
  • (?=[^a-z]*[a-z]) Assert optional chars other than a-z, then match a char a-z
  • [a-z@$!%*?&]* Match all allowed characters without a digit
  • \d Match at least a single digit
  • [a-z\d@$!%*?&]* Match optional allowed characters
  • $ End of string

See a regex demo

In JavaScript:

const regex = /^(?=[^a-z]*[a-z])[a-z@$!%*?&]*\d[a-z\d@$!%*?&]*$/i;

Note that this pattern allows a 2 character minimum.

  • Related