Reputation: 1781
I am attempting to use regex matching to get a list of optional params out of an mvc route and dynamically inject values into the holders where variables have been used. See code below. Unfortunatly the sample doesn't find both values but repeats the first. Can anyone offer any help?
using System;
using System.Text.RegularExpressions;
namespace regexTest
{
class Program
{
static void Main(string[] args)
{
var inputstr = "http://localhost:12345/Controller/Action/{route:value1}/{route:value2}";
var routeRegex = new Regex(@"(?<RouteVals>{route:[\w]+})");
var routeMatches = routeRegex.Match(inputstr);
for (var i = 0; i < routeMatches.Groups.Count; i++)
{
Console.WriteLine(routeMatches.Groups[i].Value);
}
Console.ReadLine();
}
}
}
This outputs
{route:value1}
{route:value1}
where I was hopeing to get
{route:value1}
{route:value2}
Upvotes: 2
Views: 6607
Reputation: 40145
foreach (Match match in routeMatches){
for(var i=1;i<match.Groups.Count;++i)
Console.WriteLine(match.Groups[i].Value);
}
Upvotes: 0
Reputation: 26930
Just make a global match :
var inputstr = "http://localhost:12345/Controller/Action/{route:value1}/{route:value2}";
StringCollection resultList = new StringCollection();
Regex regexObj = new Regex(@"\{route:\w+\}");
Match matchResult = regexObj.Match(inputstr);
while (matchResult.Success) {
resultList.Add(matchResult.Value);
matchResult = matchResult.NextMatch();
}
Your results will be stored in resultList.
Upvotes: 1