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

JCC*_*CyC 0 c# regex

假设我匹配的是具有这样的子表达式的模式:

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);
Run Code Online (Sandbox Code Playgroud)

在第一场比赛中,我想恢复第一个子表达式匹配"man"(而不是"woman"或"couple")和第二个子表达式匹配"woman"(而不是"man"或"couple")的信息或"aardvark").而第二场比赛是"男人"和"男人"等.这个信息在Match对象的某个地方可用吗?

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

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

得到"男人寻求女人".但我不知道该字符串的哪些部分来自哪个子表达式.

Rub*_*ias 5

试试这个:

myMatch.Groups[0] // "man seeking woman"
myMatch.Groups[1] // "man"
myMatch.Groups[2] // "woman"
Run Code Online (Sandbox Code Playgroud)

编辑:要使答案更完整,如果你有:

new Regex("(?<seeker>man|woman|couple) seeking (?<target>man|woman|couple)");
Run Code Online (Sandbox Code Playgroud)

您可以使用:

myMatch.Groups["seeker"] // "man"
myMatch.Groups["target"] // "woman"
Run Code Online (Sandbox Code Playgroud)

  • 团体+1.请记住,你可以在.net中命名群组,如(?<seeker>(man | woman | couple)),可以让你用myMatch.Groups ["寻求者"]识别群组 (2认同)