[英]Extracting into named groups parts of a url via Regex
我正在嘗試使用Regex for .Net獲取帶有命名組的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
或者取決於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)
這意味着我缺少一些可選的東西?:(),但我似乎無法看到哪里,認為我有太多的正則表達式一天:)
如果有人能幫助我,我將不勝感激。
你的問題是你的正則表達式中有太多的斜杠( /
)。 也就是說,你有一個在一個部分的末尾,然后是下一個部分的開頭。 修復它的最簡單方法是在每個部分的末尾加上斜杠:
^/find/products/(?<Query>\w*/)?
(?<SubsQuery>with/(?<Subset>\w*/)?)?
(?<PageQuery>page/(?<Page>\d/)?)?
$
當然,這會將斜杠放入您的命名組中。 要刪除它們,您需要更多組:
^/find/products/((?<Query>\w*)/)?
(?<SubsQuery>with/((?<Subset>\w*)/)?)?
(?<PageQuery>page/((?<Page>\d)/)?)?
$
試試吧
Match result = Regex.Match(str, @"^/find/products/(?<Query>\w*)?/?
(?<SubsQuery>with/(?<Subset>\w*))?/?
(?<PageQuery>page/(?<Page>\d)?/)?
$",
RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
問題是,您錯過了例如“/ find / products / test /”中的最后一個斜杠,因為這是從下一個(不可用)組中覆蓋的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.