【问题标题】:Regex Split String at particular word正则表达式在特定单词处拆分字符串
【发布时间】:2014-10-07 08:21:30
【问题描述】:

我想使用Regex.Split 方法将此输入string 拆分为array。它必须对单词进行分组。

输入:**AAA**-1111,**AAA**-666,**SMT**-QWQE,**SMT**-TTTR

预期输出:

**AAA** : 1111,666

**SMT** : QWQE,TTTR

我需要使用什么模式?

【问题讨论】:

  • 任意数量条目的通用解决方案:按,拆分,排序,然后按-拆分,然后分组。

标签: .net c# .net regex string-split


【解决方案1】:

正如对问题的评论,您不能一步完成(无论是否使用正则表达式)。

所以:

  1. 以逗号分隔。
  2. 在破折号上分开(但保留成对)
  3. 按每对的第一部分分组。

类似:

var result = select outer in input.Split(",")
             let p = outer.Split('-')  // will be string[2]
             select new { identifier = p[0], value = p[1] }
             into pair
             group by pair.identifier into g
             select new {
               identifier = g.Key
               values = String.Join(",", g)
             }

【讨论】:

    【解决方案2】:

    这应该给你一个带有key-string 和一个字符串列表(用逗号分隔)values 前面的 IEnumerable:

    var input =  "AAA-1111,AAA-666,SMT-QWQE,SMT-TTTR";
    
    var list = input.Split(',')
                    .Select(pair => pair.Split('-'))
                    .GroupBy(pair => pair.First())
                    .Select(grp => 
                                new{
                                    key = grp.Key, 
                                    items = String.Join(",", grp.Select(x => x[1])) 
                                   });
    

    然后您可以像这样使用它(如果您只想输出值):

    string output = "";
    foreach(var grp in list)
    {
        output += grp.key + ": " + grp.items + Environment.NewLine;
    }
    

    【讨论】:

      【解决方案3】:

      FWIW 使用流利的语法提供相同的解决方案,可能更容易理解:

      string input = "AAA-1111,AAA-666,SMT-QWQE,SMT-TTTR";
      
      Dictionary<string, string> output = input.Split(',') // first split by ','
          .Select(el => el.Split('-')) // then split each inner element by '-'
          .GroupBy(el => el.ElementAt(0), el => el.ElementAt(1)) // group by the part that comes before '-'
          .ToDictionary(grp => grp.Key, grp => string.Join(",", grp)); // convert to a dictionary with comma separated values
      

      -

      output["AAA"] // 1111,666
      output["SMT"] // QWQE,TTTR
      

      【讨论】:

        猜你喜欢
        • 2022-08-21
        • 1970-01-01
        • 2011-10-06
        • 2013-08-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多