我有一些字符串对应于由空格分隔的单词,并且可以使用括号进行分组。我还有一个字符串数组,表示字符串中存在的组(不一定按相同的顺序)。这是一个例子:myString = "zzz AND (aaa AND (bbb AND ccc OR ddd) ) OR eee AND \"fff fff\" AND (ggg)"
myGroups = ["(ggg)", "(aaa AND (bbb AND ccc OR ddd) )"]我想将该查询拆分为不在引号内和不在括号内的空格。对前一个字符串进行分割的输出如下:["zzz", "AND", "(aaa AND (bbb AND ccc OR ddd) )", "OR", "eee", "AND", "\"fff fff\"", "AND", "(ggg)"]我成功地使用正则表达式分割了不在引号内的空格\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)但我正在努力在其中添加群体的概念。笔记 :myString可能包含嵌套组,但我只想在外部组上拆分无需处理括号语法错误的情况
2 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
// PHP
$re = '/(\((([^()]*|(?1))*)\))|(\\\\"[^\\\\]+\\\\"|[^\s]+)/m';
$str = 'zzz AND (aaa AND (bbb AND ccc OR ddd) ) OR eee AND \\"fff fff\\" AND (ggg)';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
$result = array_column($matches, 0);
print_r($result);
// output
Array
(
[0] => zzz
[1] => AND
[2] => (aaa AND (bbb AND ccc OR ddd) )
[3] => OR
[4] => eee
[5] => AND
[6] => \"fff fff\"
[7] => AND
[8] => (ggg)
)
- 2 回答
- 0 关注
- 81 浏览
添加回答
举报
0/150
提交
取消