繁体   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