2011-11-02 45 views
2

我試圖使用正則表達式匹配從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} 

我在那裏hopeing得到

{route:value1} 
{route:value2} 

回答

1

我什麼都不知道C#,但如果你把量詞收盤parenthese後,它可以幫助,沒有?

更新:That post可能會幫助你。

+0

你可以測試簡化的定義:'new Regex(「({route:[\ w]})+」);'? – Renaud

+1

雷諾,你已經解決了,謝謝。您提到的帖子顯示我應該使用匹配不匹配.... var routeMatches = routeRegex.Matches(inputstr); (var i = 0; i

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。

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

嗨Bluepixy,感謝您的評論。但要注意的重要一點是,爲了枚舉routeMatches,您必須調用.Match()不是.Match()纔可以提取所有匹配,因爲Matches()返回MatchCollection,Match()只返回Match。然後,您可以按照您在此處完成的結果查詢結果,也可以在我對Renaud的回覆中提到的結果。 –