使用正则表达式使用捕获组进行多次匹配

时间:2011-11-02 19:24:31

标签: c# regex match

我试图使用正则表达式匹配从mvc路由中获取可选参数列表,并动态地将值注入到已使用变量的持有者中。见下面的代码。不幸的是,样本没有找到两个值,但重复第一个。任何人都可以提供任何帮助吗?

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();
        }
    }
}

此输出

{route:value1}
{route:value1}

我希望得到的地方

{route:value1}
{route:value2}

3 个答案:

答案 0 :(得分:1)

我对C#一无所知但是如果你把之后放在关闭的括号中,它会有所帮助吗?

更新: That post可能会对您有所帮助。

答案 1 :(得分:1)

刚刚进行全球比赛:

    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();
    }

您的结果将存储在resultList中。

答案 2 :(得分:0)

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