Home > Software design >  php validate a pattern with regex
php validate a pattern with regex

Time:09-15

I try to validate a pattern like 123*5000. The pattern has 3 parts.

First, the [123] must contain three digits unique number. The second is *, and the third is 5000, must be an integer, not unique is fine.

If the pattern is 223*443 it will return false (first part 223, number 2 it not unique).

If the pattern is 908*22 it will return true (first part contain unique number, second part is *, third part is integer).

If the pattern is 34*5000 it will return false (first part only contain 2 digits), and etc.

I try regex \^[0-9][0-9][0-9][*][0-9] $\ but it did not solve the first part pattern that must contains unique number.

Can anyone help me?

CodePudding user response:

You might write the pattern as:

^(?!\d*(\d)\d*\1)\d{3}\*\d $

The pattern matches:

  • ^ Start of string
  • (?!\d*(\d)\d*\1) Negative lookahead, assert not 2 of the same digits
  • \d{3}\*\d Match 3 digits, then * and 1 or more digits
  • $ End of string

See a regex demo.

  • Related