【问题标题】:C# regex - not getting outer groupC# 正则表达式 - 没有得到外部组
【发布时间】:2012-01-18 13:30:21
【问题描述】:

我正在使用以下正则表达式来查找组

string pattern = @"(?<member>(?>\w+))\((?:(?<parameter>(?:(?>[^,()""']+)|""(?>[^\\""]+|\\"")*""|@""(?>[^""]+|"""")*""|'(?:[^']|\\')*'|\((?:(?<nest>\()|(?<-nest>\))|(?>[^()]+))*(?(nest)(?!))\))+)\s*(?(?=,),\s*|(?=\))))+\)";

来自像

这样的表达式
string Exp = "GetValue(GetValue(GetValue(1 + 2) * GetValue(3 * 4)) / GetValue(GetValue(5 * 6) / 7) / 8)";  

我得到以下组:

a) GetValue(GetValue(1 + 2) * GetValue(3 * 4))

b) 获取值(GetValue(5 * 6) / 7)

我得到了所有组,但外部组 (GetValue(.... / 8)) 没有得到???

模式中可能有什么问题??

【问题讨论】:

  • 我尝试创建一个正则表达式,但它根本不匹配:regexr.com?2voqv
  • 你能进一步解释一下想要的结果吗?具体来说,您希望在每个组中捕获什么:成员、参数、嵌套、-nest。

标签: c# regex


【解决方案1】:

我最好的帮助是下载和使用这个 RegexDesigner

http://www.radsoftware.com.au/regexdesigner/

【讨论】:

    【解决方案2】:

    由于它是一个复杂的正则表达式,因此最好为您的搜索字符串提供一个实际示例。我发现在大多数情况下,您需要进行贪婪的 RegEx 匹配。

    例如:

    Non-Greedy:
    "a.+?b":
    
    Greedy:
    "a.*b":
    

    【讨论】:

      【解决方案3】:

      如果您尝试进行以下匹配,则单独使用正则表达式是不可能的:

      1. GetValue(GetValue(GetValue(1 + 2) * GetValue(3 * 4)) / GetValue(GetValue(5 * 6) / 7) / 8)
      2. GetValue(GetValue(1 + 2) * GetValue(3 * 4))
      3. GetValue(1 + 2)
      4. GetValue(3 * 4)
      5. GetValue(GetValue(5 * 6) / 7) / 8)
      6. GetValue(5 * 6) / 7)

      请参阅this article 了解原因。但是,您可以使用递归来获取匹配项中的匹配项,例如(未经测试的伪代码):

      private List<string> getEmAll(string search)
      {
          var matches = (new Regex(@"Your Expression Here")).Match(search);
          var ret = new List<string>();
          while (matches.Success)
          {
              ret.Add(matches.Value);
              ret.AddRange(getEmAll(matches.Value));
              matches = matches.NextMatch();
          }
          return ret;
      }
      
      ...
      
      getEmAll("GetValue(GetValue(GetValue(1 + 2) * GetValue(3 * 4)) / GetValue(GetValue(5 * 6) / 7) / 8)");
      

      如果您想将匹配进一步分成匹配组,那会稍微复杂一些 - 但您明白了要点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-23
        • 2017-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多