Search code examples
phpregexpreg-match

Create regular expression which satisfy multiple conditions


I am trying to create a regular expression using the below restriction, but maybe I am missing something, because it creates a wrong output.

Restrictions:

1) String shouldn't contain numbers only

2) String shouldn't contain more than 3 special characters

3) String has not any word (substring) which has length more than 10 characters

4) String length must be 3 or greater

I have created a regex which solves the 1st point:

/^\d*[a-zA-Z][a-zA-Z\d]*$/

But I failed with adding the other restrictions 2-4.


Solution

  • You may use a regex like

    ^(?!\d+$)(?!(?:[^$&%@]*[$&%@]){4})(?!.*\b\w{11}).{3,}$
    

    See the regex demo

    Pattern breakdown:

    • ^ - start of string
    • (?!\d+$) - there must not be only digits (\d+) up to the end of string ($)
    • (?!(?:[^$&%@]*[$&%@]){4}) - there must not be 4 sequences of 0+ non-special characters ([^$&%@]*) followed with a special character
    • (?!.*\b\w{11}) - there must not be a word having 11 word characters (\w{11}) after a word boundary (\b)
    • .{3,} - 3+ any characters
    • $ - end of string