Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何获取MatchCollection中匹配项的索引?_C#_Regex - Fatal编程技术网

C# 如何获取MatchCollection中匹配项的索引?

C# 如何获取MatchCollection中匹配项的索引?,c#,regex,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 = b

例如:

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

我正在查看这里的文档,除了将匹配集合转换为数组之外,没有看到任何有用的方法

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
}

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
}

您试图解决的实际问题是什么?当使用string.Split()方法更容易时,为什么要对这个简单字符串使用Regex,该方法给出并索引:string[]results=url.Split(new char[]{'/'});对,没有这个办法。您需要将匹配项拉入一个具有更多功能的集合。@jdweng这只是一个示例。在我的特定用例中,我确实需要一组括号内的通配符。您想要做的是不明确的。您需要一个更复杂的正则表达式,因为您当前的正则表达式没有包含足够的信息。可能有一个命名的捕获组与“仅包含数字的方括号”匹配——您可以假定该匹配为
id
(您将该组命名为“id”),然后另一个组与“仅包含字母和空格的方括号”匹配,您可以假定该匹配为
name
字段。或者假设
name
始终是第一对方括号,
id
始终是第二对方括号,并验证是否有2个匹配项(希望正则表达式总是有序的)。您试图解决的实际问题是什么?为什么要对这个简单字符串使用正则表达式,因为它更易于使用字符串。Split()给出和索引的方法:String[]results=url.Split(新字符[]{'/'});对,没有这个办法。您需要将匹配项拉入一个具有更多功能的集合。@jdweng这只是一个示例。在我的特定用例中,我确实需要一组括号内的通配符。您想要做的是不明确的。您需要一个更复杂的正则表达式,因为您当前的正则表达式没有包含足够的信息。可能有一个命名的捕获组与“仅包含数字的方括号”匹配——您可以假定该匹配为
id
(您将该组命名为“id”),然后另一个组与“仅包含字母和空格的方括号”匹配,您可以假定该匹配为
name
字段。或者假设
name
始终是第一对括号,
id
始终是第二对括号,并验证是否有2个匹配项(希望正则表达式总是有序的)。