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

PHP Regex Match ! or * anywhere in string

I’m a beginner in using Regex and have been struggling to create a pattern that can search for a single match of either ! or * anywhere in my string. The full requirements I am looking for are:

  • Start with a letter
  • Contain at least 1 number
  • Between 8-16 characters
  • Contain at least one ! or *

What I have so far is:

^[A-Za-z](!*)[A-Za-z0-9]{6,14}$

Clearly I’m using parenthesis incorrectly, but I’m still playing around with it and trying different things. What I am specifically struggling with is searching for a single instance of ! or * in any location.

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

If anyone can kindly provide a hint, it would be appreciated.

>Solution :

You may use this regex:

^[A-Za-z](?=.*[!*])(?=.*\d).{7,15}$

RegEx Demo

Explanation:

  • ^: Start
  • [A-Za-z]: Match a letter
  • (?=.*[!*]): Lookahead to assert that we have at least one * or !
  • (?=.*\d): Lookahead to assert that we have at least one digit
  • .{7,15}$: Match 7 to 15 characters (we matched a letter at start)
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