我需要一个正则表达式使用逗号(,)分隔符来分割字符串,但是在下面的示例中忽略逗号是否用大括号{,}括起来;
"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"
问题:(不是这样)
"asd"
domain={"id"="test"}
names={"index"="user.all"
"show"="user.view"}
test="test"
我尝试过此操作,但它也将大括号{,}中的逗号分隔
\{[^}]*}|[^,]+
但是我完全不知道最终应该如何解决。任何帮助都将被申请!
我看到了可能性(不会因长字符串而崩溃):
第一个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]);
第二个withpreg_split
和backtracking控制动词可避免将部分括在大括号之间(较短的字符串,但对于长字符串而言效率较低):
$pattern = '~{[^}]*}?(*SKIP)(*F)|,~';
print_r(preg_split($pattern, $str));
(*F)
强制模式失败,并(*SKIP)
强制正则表达式引擎跳过模式失败时已经匹配的部分。
最后一种方法的缺点是模式以交替开始。这意味着对于不是a{
或a的每个字符,,
将测试交替的两个分支(不作任何选择)。但是,您可以使用S
(study)修饰符来改善模式:
$pattern = '~{[^}]*}?(*SKIP)(*F)|,~S';
或者您也可以不作任何更改地编写它,如下所示:
$pattern = '~[{,](?:(?<={)[^}]*}?(*SKIP)(*F))?~';
通过这种方式,之前使用{
或的,
位置的搜索算法要比正则表达式引擎的正常遍历更快。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句