【问题标题】:Extracting tokens from a string with regular expressions in .NET在 .NET 中使用正则表达式从字符串中提取标记
【发布时间】:2011-05-02 08:25:52
【问题描述】:

我很好奇这是否可以使用正则表达式。我想从类似于以下的字符串中提取标记:

Select a [COLOR] and a [SIZE].

好的,很简单 - 我可以使用(\[[A-Z]+\])

但是,我还想提取标记之间的文本。基本上,我希望上述匹配组是:

"Select a "
"[COLOR]"
" and a "
"[SIZE]"
"."

最好的方法是什么?如果有办法用 RegEx 做到这一点,那就太好了。否则,我猜我必须提取标记,然后手动循环 MatchCollection 并根据每个匹配的索引和长度解析出子字符串。请注意,我需要保留字符串和标记的顺序。有没有更好的算法来做这种字符串解析?

【问题讨论】:

    标签: c# .net regex algorithm


    【解决方案1】:

    使用Regex.Split(s, @"(\[[A-Z]+\])") - 它应该为您提供所需的确切数组。 Split 获取捕获的组并将它们转换为结果数组中的标记。

    【讨论】:

      【解决方案2】:

      这是一个不使用正则表达式 (Regex) 的方法,它使用了String.Split,但是你会丢失分隔符。

              string s = "Select a [COLOR] and a [SIZE].";
      
              string[] sParts = s.Split('[', ']');
      
              foreach (string sPart in sParts)
              {
                  Debug.WriteLine(sPart);
              }
      
              // Select a 
              // COLOR
              //  and a 
              // SIZE
              // .
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-17
        • 2014-10-17
        • 1970-01-01
        • 1970-01-01
        • 2020-12-19
        • 2014-08-25
        • 1970-01-01
        • 2010-10-14
        相关资源
        最近更新 更多