Shahensha Khan
Shahensha Khan

Reputation: 265

Regex in php to validate a pattern

I have got into some issue related to regular expression and patterns. my input has to be either in format of A or B or combination of A and B several times.

to illustrate it

A pattern is x(y)

B pattern is x(y,z)

A,B means x(y),x(y,z)

Combinations can be like but not limited to

A,A

A,A,A

A,B,A

B,B

B,B,B

and so on with no specific numbers per combination. is there any available method to verify if A and B in the combination are in the right format.

what I think I should do is to split the combination at a delimiter and then pass each array element through a function which validates my A and B.

$rule=$_POST['rule'];                             //e,g aaa(bbb,ccc) OR aaa(bbb)
$patternR1='/^\w+[\(]\w+[\)]$/';
$patternR2='/^\w+[\(]\w+[\,]\w+[\)]$/';
if (preg_match($patternR1, $rule ))
    {
        echo "Your entered rule is ".$rule." satisfying the correct format: x(y)";

    }
    else if(preg_match($patternR2, $rule))
    {
        echo "Your entered rule is ".$rule." satisfying the correct format: x(y,z)";
    }
    else 
    {
        echo "Syntax error in the rule body ". $rule." has to be either in x(y) or x(y,z) format";
        $ef=0;
    }

Also please note that there is one comma which separates A and B and there is comma inside the pattern B which have different meaning in the context.

Upvotes: 2

Views: 107

Answers (1)

Havelock
Havelock

Reputation: 6968

The RegExp you're looking for is

/^(?<foo>\w\(\w(,\w)?\))(,(?&foo))*$/gi

and you could test it and play around with it here

So the pattern named foo generalises what you named A and B, that is \w\(\w(,\w)?\). Then we allow recursion of that pattern with a preceding comma. That's it.

Upvotes: 5

Related Questions