Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Build a Regex with following conditions:

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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@$!%*?&()]*$'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading