代码之家  ›  专栏  ›  技术社区  ›  JCCyC

如何从正则表达式匹配中获取匹配的子表达式?(C#)

  •  0
  • JCCyC  · 技术社区  · 16 年前

    假设我正在匹配一个模式,该模式有如下子表达式:

    Regex myRegex = new Regex("(man|woman|couple) seeking (man|woman|couple|aardvark)");
    
    string myStraightText = "Type is man seeking woman, age is 44";
    MatchCollection myStraightMatches = myRegex.Matches(myStraightText);
    
    string myGayText = "Type is man seeking man, age is 39";
    MatchCollection myGayMatches = myRegex.Matches(myGayText);
    
    string myBizarreText = "Type is couple seeking aardvark, age is N/A";
    MatchCollection myBizarreMatches = myRegex.Matches(myBizarreText);
    

    在第一个匹配中,我想恢复第一个子表达式匹配“man”(而不是“woman”或“particle”)的信息,第二个子表达式匹配“woman”(而不是“man”或“particle”或“aardvark”)。而第二个匹配是“人”和“人”等。这个信息在 Match 对象

    我只知道如何获得完整的匹配字符串。例如,

    foreach (Match myMatch in myStraightMatches)
    {
        tbOutput.Text += String.Format("{0}\n", myMatch);
    }
    

    2 回复  |  直到 16 年前
        1
  •  5
  •   Rubens Farias    16 年前

    试试这个:

    myMatch.Groups[0] // "man seeking woman"
    myMatch.Groups[1] // "man"
    myMatch.Groups[2] // "woman"
    

    编辑

    new Regex("(?<seeker>man|woman|couple) seeking (?<target>man|woman|couple)");
    

    您可以使用:

    myMatch.Groups["seeker"] // "man"
    myMatch.Groups["target"] // "woman"
    
        2
  •  3
  •   Kennet Belenky    16 年前

    您可以按照Rubens Farias的建议使用编号组。然而,对于程序员的小错误或随后对正则表达式的更改,编号组往往是脆弱的。

    我通常尝试使用命名组。语法看起来像 (?<name>...)

    然后,您可以这样引用组:

    myMatch.Groups["name"]