簡體   English   中英

在C#中使用Regex在一個分隔符例外的情況下通過分隔符將字符串解析為數組/列表

[英]Using Regex in C# to parse a string into an array/list by delimiter with one delimiter exception

我的輸入字符串:

var s = "{1, >, [4,6,7,8], a, b, [x,y], d, 9}";

我想刪除{}並獲得一個數組,每個元素之間用逗號分隔,但逗號在[]內時除外-括號中的所有內容都將作為沒有括號的自身元素返回。

所需的輸出List <String>String [],其內容為:

1
>
4,6,7,8
a
b
x,y
d
9

預計到達時間:這是我的UnitText(xunit),它測試@ washington-guedes建議的每個模式,並帶有一個參數以修剪空白輸入字符串。 在清理WS的兩種情況下,測試均失敗。

    [Theory]
    [InlineData(@"([^{\s]+(?=(?:,|})))", false)]
    [InlineData(@"([^{\s]+(?=(?:,|})))", true)]
    [InlineData(@"([^{\s[\]]+(?=(?:]|,|})))", false)]
    [InlineData(@"([^{\s[\]]+(?=(?:]|,|})))", true)]
    public void SO(string pattern, bool trimWS)
    {
        //Arrange
        var exp = "{1, >, [4,6,7,8], a, b, [x,y], d, 9}";
        if (trimWS)
            exp = exp.Replace(" ", "");
        Match match = Regex.Match(exp, pattern);
        var list = new List<String>();
        while (match.Success)
        {
            list.Add(match.Value);
            match = match.NextMatch();
        }
        Assert.Equal(8, list.Count);
    }

試試這個正則表達式:

((?<=,\[)[^]]+)|((?<={)[^,}]+)|((?<=,)(?!\[)[^,}]+)

正則表達式住在這里。

解釋:

(                  # start of capturing group
  (?<=,\[)         # starting with ",["
  [^]]+            # matches all till next "]"
)                  # end of capturing group

  |                # OR

(
    (?<={)         # starting with "{"
    [^,}]+         # matches all till next "," or "}"
)

  |                # OR

(
    (?<=,)(?!\[)   # starting with "," and not a "["
    [^,}]+         # matches all till next "," or "}"
)

希望能幫助到你。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM