Seeker
Seeker

Reputation: 1927

Conditional Regex If Number is +1 or equal to a specific number behind in string

I have a regular expression:

 /^ETW([0-9C])([0-9])([0-9])([0-9])([0-9])([A-L])([0-9])([0-9])([0-9])/g

Which matches the following things:

  1. Character 1 is always the alpha character – E
  2. Character 2 is always the alpha character – T
  3. Character 3 is always the alpha character – W
  4. Character 4 may only be any numeric digit 0 – 9 or the alpha character C (No other alpha characters are allowed)
  5. Character 5 may only be any numeric digit 0 – 9 (No alpha characters)
  6. Character 6 may only be any numeric digit 0 – 9 (No alpha characters)
  7. Character 7 may only be any numeric digit 0 – 9 (No alpha characters)
  8. Character 8 may only be any numeric digit 0 – 9 (No alpha characters)
  9. Character 9 is always one of the following alpha characters –A, B, C, D, E, F, G, H, I, J, K, L (No other alpha characters are allowed)
  10. Character 10 may only be any numeric digit 0 – 9 (No alpha characters)
  11. Character 11 may only be any numeric digit 0 – 9 (No alpha characters)
  12. Character 12 may only be any numeric digit 0 – 9 (No alpha characters)

All these conditions are fulfilling with my RegEx but problem is now another condition is added that the Character 12 can only be Equal to Character 10 or +1 only from Character 10

How can i achieve this ?? i have tried Conditional RegEx but its not working can anyone help me out with this ?? Do i have to handle it with pragmatically i am sorry i am really new to RegEx conditional handling any helping material will also be useful.

Upvotes: 1

Views: 315

Answers (1)

MDEV
MDEV

Reputation: 10838

One way would be to split it into two separate match operations, using the result from the first one to create the second.

function isValidFormat($str)
{
    $pt1 = substr($str,0,10);
    $r1 = '#^ETW(\d|C)(\d)(\d)(\d)(\d)([A-L])(\d)#';
    //If you're not going to use all the match groups, use
    //$r1 = '#^ETW(\d|C)\d{4}[A-L](\d)#';
    //And instead of $matches[7], use $matches[2]
    if(preg_match($r1,$pt1,$matches)>0)
    {
        $pt2 = substr($str,10);
        $pt10 = intval($matches[7]);
        $pt12M = $pt10==9 ? '9' : '('.$pt10.'|'.($pt10+1).')$';
        $r2 = '#\d'.$pt12M.'$#';
        return preg_match($r2,$pt2)>0;
    }
    else return false;
}
$isValid = isValidFormat('ETW09876D929');
var_dump($isValid);

You visit this link and hit run/F9 to test

Upvotes: 2

Related Questions