C#没有得到外部组

本文关键字:外部 | 更新日期: 2023-09-27 18:20:34

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

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(GetValue(5*6)/7)

我正在获取所有组,但外部组(GetValue(…./8))没有获取???

模式中可能存在什么问题??

C#没有得到外部组

我对您最好的帮助是下载并使用此RegexDesigner

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

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

例如:

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

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

  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)

请参阅本文了解原因。然而,您可以使用递归来获得匹配中的匹配,例如(未经测试的伪代码):

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)");

如果你想把比赛进一步分成匹配的小组,这会稍微复杂一些,但你明白要点了。