简体   繁体   English

正则表达式分割逗号分隔括号,应该很容易

[英]Regular Expression Split Comma Separated Braces, Should Be Easy

To all: I have this string: 对所有人:我有这个字符串:

"{1,2,3},{4},{3}"

That I want to split to an array like this: 我想拆分成这样的数组:

    {1,2,3}
    {4}
    {3}

The pattern I am using ",\\{([^)]*)\\}," is only partially working and giving me an array of: 我正在使用的模式",\\{([^)]*)\\},"只是部分工作,给我一个数组:

    {1,2,3}
    4
    {3}

I am doing this: 我这样做:

string[] strs = Regex.Split(string, pattern)

I can't figure out what I am missing so that the 2nd value is missing the braces. 我无法弄清楚我错过了什么,以便第二个值缺少大括号。 I've been banging my head against the wall. 我一直在撞墙。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thanks! 谢谢!

You can use the following regex to split: 您可以使用以下正则表达式进行拆分:

(?<=\}),(?=\{)

This matches all commas , that are preceded by } and have } after them. 这匹配所有逗号,前面有}并且后面有}

RegexHero Demo RegexHero演示

you can just use split andd add the pare you've put out: 你可以使用split andd添加你已经推出的削减:

string[] splitted = str.Split("},{");


for(int i = 0; i < splitted.Count ; i++)
{
  if(i != 0)
  {
     Console.WriteLine("{");
  }
  Console.WriteLine(curr[i]);
  if(i != splitted.Count - 1)
  {
      Console.WriteLine("}");
  }
}

The "pure Regex" answer is like this: “纯正的正则表达式”的答案是这样的:

        string str = "{1,2,3},{4},{3}";
        string[] strs =
            Regex.Matches(str, @"({.*?})")
                 .OfType<Match>()
                 .Select(m => m.Groups[0].Value)
                 .ToArray();

which is more tolerant of different - or even mixed - separators between the braced groups, such as comma-space or space rather than just a comma. 它更能容忍支撑组之间的不同 - 甚至是混合 - 分隔符,例如逗号空间或空格而不仅仅是逗号。 If your input string is well-defined then this won't be an issue, but I prefer to be able to handle inputs which might come from different sources and might not quite conform. 如果你的输入字符串是明确定义的,那么这不会是一个问题,但我更喜欢能够处理可能来自不同来源并且可能不完全符合的输入。

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

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