簡體   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