我遇到了一些与正则表达式和模式有关的问题。 我的输入必须是A或B的格式或A和B的组合多次。
来说明它
模式是x(y)
B模式是x(y,z)
A,B表示x(y),x(y,z)
组合可以是但不限于
A,A
A,A,A
A,B,A
B,B
B,B,B
等等,每个组合没有特定的数字。 是否有任何可用的方法来验证组合中的A和B是否格式正确。
我认为我应该做的是在分隔符处拆分组合,然后通过一个验证我的A和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;
}
另请注意,有一个逗号分隔A和B,模式B中有逗号,在上下文中有不同的含义。
答案 0 :(得分:4)
您正在寻找的RegExp是
/^(?<foo>\w\(\w(,\w)?\))(,(?&foo))*$/gi
你可以测试它并玩它here
因此,名为foo
的模式概括了您命名为A
和B
的内容,即\w\(\w(,\w)?\)
。然后我们允许使用前面的逗号递归该模式。那就是它。