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

本文关键字:索引 获取 MatchCollection | 更新日期: 2023-09-27 17:58:04

示例:

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,除了将我的匹配集合转换为数组之外,看不到任何有用的方法。

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

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

您需要像这个一样迭代MatchCollection中的每个Match

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
}