2011-11-28 46 views
0

我試圖讓與命名組與正則表達式的URL部分地區的淨提取到一個URL的命名組部分通過正則表達式

的例子是

/find/products/ 
/find/products/test/ 
/find/products/test/with/ 
/find/products/test/with/lids/ 
/find/products/test/page/3/ 
/find/products/test/with/lids/page/3/ 

從正則表達式的結果應該是

Query: Test 
Subset: Lids 
Page: 3 

或null取決於url,我想命名組,以便我可以稍後動態提取它。

我的嘗試是

^/find/products/(?<Query>\w*)? 
(?<SubsQuery>/with/(?<Subset>\w*)?/)? 
(?<PageQuery>/page/(?<Page>\d)?/)? 
$ 

從例如

/find/products/ (matches) 
/find/products/test/ (doesnt) 
/find/products/test/with/ (doesnt) 
/find/products/test/with/lids/ (matches) 
/find/products/test/page/3/ (matches) 
/find/products/test/with/lids/page/3/ (doesnt) 

這意味着我失去了一些可選的東西?:(),但我似乎無法看到,我想有一天有太多的正則表達式:)

如果任何人都可以幫助我,將不勝感激。

回答

1

試試這個位置

Match result = Regex.Match(str, @"^/find/products/(?<Query>\w*)?/? 
    (?<SubsQuery>with/(?<Subset>\w*))?/? 
    (?<PageQuery>page/(?<Page>\d)?/)? 
    $", 
    RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); 

的問題是,你錯過例如最後一個斜線「/ find/products/test /」,因爲這是從下一個(不可用)組中覆蓋的。

+0

這工作完美,我看起來很盲目:) – Sarkie

1

你的問題是你的正則表達式中有太多斜線(/)。也就是說,你在一個部分的末尾有一個,然後是下一個部分的開始。要解決這個問題最簡單的方法是在每部分的末尾有斜槓:

^/find/products/(?<Query>\w*/)? 
(?<SubsQuery>with/(?<Subset>\w*/)?)? 
(?<PageQuery>page/(?<Page>\d/)?)? 
$ 

當然,這把斜線到您的命名組。爲了消除它們,你需要更多的羣體:

^/find/products/((?<Query>\w*)/)? 
(?<SubsQuery>with/((?<Subset>\w*)/)?)? 
(?<PageQuery>page/((?<Page>\d)/)?)? 
$ 
+0

我認爲stema的回答稍微好一些,因爲它沒有沒有名字的組,但是你的很有用,所以謝謝! – Sarkie