Skip to content
Advertisement

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.

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

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement