我有一些字符串對(duì)應(yīng)于由空格分隔的單詞,并且可以使用括號(hào)進(jìn)行分組。我還有一個(gè)字符串?dāng)?shù)組,表示字符串中存在的組(不一定按相同的順序)。這是一個(gè)例子: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) )"]我想將該查詢拆分為不在引號(hào)內(nèi)和不在括號(hào)內(nèi)的空格。對(duì)前一個(gè)字符串進(jìn)行分割的輸出如下:["zzz", "AND", "(aaa AND (bbb AND ccc OR ddd) )", "OR", "eee", "AND", "\"fff fff\"", "AND", "(ggg)"]我成功地使用正則表達(dá)式分割了不在引號(hào)內(nèi)的空格\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)但我正在努力在其中添加群體的概念。筆記 :myString可能包含嵌套組,但我只想在外部組上拆分無(wú)需處理括號(hào)語(yǔ)法錯(cuò)誤的情況
2 回答

慕田峪9158850
TA貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
// 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 關(guān)注
- 131 瀏覽
添加回答
舉報(bào)
0/150
提交
取消