如何在MatchCollection中获取匹配的索引?

时间:2016-07-21 22:11:26

标签: c# regex

示例:

Regex inBrackets = new Regex(@"\{(.*?)\}");
String url = "foo/bar/{name}/{id}"; 
MatchCollection bracketMatches = inBrackets.Matches(url); 
int indexOfId = bracketMatches.IndexOf("name"); // equals 0 if IndexOf was a real method
int indexOfId = bracketMatches.IndexOf("id"); // equals 1 if IndexOf was a real method

我正在查看此处的文档https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection(v=vs.110).aspx,除了将我的匹配集合转换为数组之外,我们没有看到任何有用的方法。

1 个答案:

答案 0 :(得分:2)

MatchCollection可以包含多个匹配项,从包含0,1或多个匹配项的集合中获取索引是没有意义的。

您希望迭代Match中的每个MatchCollection

foreach (Match match in bracketMatches){
    // Use match.Index to get the index of the current match
    // match.Value will contain the capturing group, "foo", "bar", etc
}