chrisp_68
chrisp_68

Reputation: 1781

Using regex to match multiple times using capturing group

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

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

foreach (Match match in routeMatches){
    for(var i=1;i<match.Groups.Count;++i)
        Console.WriteLine(match.Groups[i].Value);
}

Upvotes: 0

FailedDev
FailedDev

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

Renaud
Renaud

Reputation: 8873

I know nothing about C# but it may help if you put the quantifier after the closing parenthese, no?

Update: That post may help you.

Upvotes: 1

Related Questions