【问题标题】:Select all words inside brackets (multiple matches)选择括号内的所有单词(多个匹配项)
【发布时间】:2014-11-25 18:02:10
【问题描述】:

我需要在 C# 中拆分一个字符串。我认为最好看下一个例子:

string formula="[[A]]*[[B]]"
string split = Regex.Match(formula, @"\[\[([^)]*)\]\]").Groups[1].Value;

我想得到一个包含在 '[[' 和 ']]' 之间的单词的字符串列表,所以,在这种情况下,我应该得到 'A' 和 'B',但我得到的是:A ]]*[[B

【问题讨论】:

    标签: c# regex split


    【解决方案1】:

    您的主要问题是 Regex.Match 将匹配 first 出现,然后停止。来自文档:

    在指定的输入字符串中搜索 Regex 构造函数中指定的正则表达式的第一次出现。

    您希望Regex.Matches 获取所有信息。这个正则表达式可以工作:

    \[\[(.+?)\]\]
    

    它将捕获[[]] 之间的任何内容

    所以你的代码可能看起来像:

    string formula = "[[A]]*[[B]]";
    var matches = Regex.Matches(formula, @"\[\[(.+?)\]\]");
    
    var results = (from Match m in matches select m.Groups[1].ToString()).ToList();
    
    // results contains "A" and "B"
    

    【讨论】:

      【解决方案2】:

      * 尽可能匹配它之前的表达式。使用*? 匹配可能的最小匹配项。

      http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx#quantifiers

      所以你的正则表达式应该是@"\[\[([^)]*?)\]\]"

      另外,使用Regex.Matches 而不是Regex.Match 来获取它们。

      【讨论】:

        猜你喜欢
        • 2016-10-16
        • 2014-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多