Shahensha Khan Shahensha Khan - 3 months ago 6x
PHP Question

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






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)
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)";
echo "Syntax error in the rule body ". $rule." has to be either in x(y) or x(y,z) format";

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.


The RegExp you're looking for is


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.