regexp使用逗号(,)分隔符分割字符串,但如果逗号是大括号{,}则忽略

时间:2015-12-23 10:27:28

标签: php preg-split

我需要一个正则表达式来使用逗号(,)分隔符分割字符串,但如果逗号在下面的示例中使用花括号{,}则忽略;

"asd", domain={"id"="test"}, names={"index"="user.all", "show"="user.view"}, test="test"

INTO (应该是)

"asd"
domain={"id"="test"}
names={"index"="user.all", "show"="user.view"}
test="test"

问题:(不是这样)

"asd"
domain={"id"="test"}
names={"index"="user.all"
"show"="user.view"}
test="test"

尝试了这个,但它也将逗号分隔为大括号{,}

\{[^}]*}|[^,]+

但我完全不知道这应该如何最终结束。 任何帮助都会受到欢迎!

2 个答案:

答案 0 :(得分:4)

您可以使用以下正则表达式进行拆分

(,)(?=(?:[^}]|{[^{]*})*$)

因此,使用preg_split可以像

那样使用
echo preg_split('/(,)(?=(?:[^}]|{[^{]*})*$)/',$your_string);

Regex

答案 1 :(得分:1)

我看到了的可能性(不会因长字符串而崩溃)

第一个$pattern = '~ (?: \G(?!\A), # contigous to the previous match, not at the start of the string | # OR \A ,?? # at the start of the string or after the first match when # it is empty )\K # discard characters on the left from match result [^{,]*+ # all that is not a { or a , (?: {[^}]*}? [^{,]* # a string enclosed between curly brackets until a , or a { # or an unclosed opening curly bracket until the end )*+ ~sx'; if (preg_match_all($pattern, $str, $m)) print_r($m[0]);

preg_split

第二个包含$pattern = '~{[^}]*}?(*SKIP)(*F)|,~'; print_r(preg_split($pattern, $str)); 和回溯控制动词,以避免大括号之间的部分(较短,但长字符串效率较低)

(*F)

(*SKIP)强制模式失败,{强制正则表达式引擎跳过模式失败时已匹配的部分。

最后一种方法的缺点是模式以交替开始。这意味着对于不是,S的每个字符,交替的两个分支都会被测试(什么都不是)。但是,您可以使用$pattern = '~{[^}]*}?(*SKIP)(*F)|,~S'; (学习)修饰符改进模式:

$pattern = '~[{,](?:(?<={)[^}]*}?(*SKIP)(*F))?~';

或者您可以不加替换地编写它,如下所示:

{

通过这种方式,使用比正则表达式引擎的正常步行更快的算法搜索具有, _db.Database.ExecuteSqlCommand("EXEC mySp"); 的位置。