Ms. Corlib
Ms. Corlib

Reputation: 5213

How can I get the index of a match in a MatchCollection?

Example:

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

I'm looking at the documentation here https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchcollection(v=vs.110).aspx and don't see any useful methods apart from converting my match collection to an array.

Upvotes: 0

Views: 2766

Answers (1)

Bradley Moorfield
Bradley Moorfield

Reputation: 877

MatchCollection can contain multiple matches, it makes no sense to get the index from a collection that could contain 0, 1, or many matches.

You'll want to iterate over each Match in the MatchCollection like this

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
}

Upvotes: 3

Related Questions