Ahsan Ul Haq Ahsan Ul Haq - 3 months ago 11
PHP Question

REGEX Build for a sequence

I want to do the validation for the String "DDP-FA12-BSE-007" using regex. Any help will be appreciated :)
tHE string is

ABC-DE12-FGH-345
or
DE12-FGH-345



  1. In first 3 places all the alphabets are Allowed.

  2. Then a -

  3. 2nd place consist of two parts. For first two places only alphabets.
    While for last two places only Digits are allowed.

  4. Then a -

  5. On 3rd place only two Alphabets are allowed.

  6. Then a -

  7. For forth place there should be only three Digits are allowed.



It should be like this
DDP-FA12-BSE-007
or
FA12-BSE-007


Ps:
DE
Should be
FA
or
SP

Answer

You can use character classes, and range limits to accomplish this regex.

^[A-Z]{3}-[A-Z]{2}\d{2}-[A-Z]{3}-\d{3}$

Demo: https://regex101.com/r/eO4dX0/1

^ is the start of the string
[A-Z] are the characters between uppercase A and Z
The {} builds a number of allowed characters of the previous group, class, or character (or a limit, if used like {1,3).
\d is a number.
$ is the end of the string.

For the PHP implementation you'll need to add delimiters:

$string = 'DDP-FA12-BSE-007';
if(preg_match('/^[A-Z]{3}-[A-Z]{2}\d{2}-[A-Z]{3}-\d{3}$/', $string)) {
     echo 'Matches';
}

Demo: https://eval.in/630376