繁体   English   中英

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

[英]regexp to split a string using comma(,) delimiter but ignore if the comma is in curly braces{,}

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

"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"

尝试了这个,但它也在括号内分隔逗号{,}

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

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

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

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

所以使用preg_split你可以像as那样做

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

正则表达式

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

第一个使用preg_match_all

$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和backtracking控制动词来避免大括号之间的部分(较短但效率较低的长字符串)

$pattern = '~{[^}]*}?(*SKIP)(*F)|,~';
print_r(preg_split($pattern, $str));

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

最后一种方法的缺点是模式以交替开始。 这意味着,对于每个字符为不是{, ,交替的两个分支被测试(白白)。 但是,您可以使用S (学习)修改器改进模式:

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

或者您可以在没有替换的情况下编写它,如下所示:

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

通过这种方式,定位与{或者,在之前比正则表达式引擎的正常行走更快的算法搜索。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM