Home > Back-end >  PHP Regex Match ! or * anywhere in string
PHP Regex Match ! or * anywhere in string

Time:08-04

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.

CodePudding user response:

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)

CodePudding user response:

You can use this pattern:

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

Here (?=.*) means that the order of things you want to exist doesn't matter but they have to be in the string at least one time.

  • Related