我正在尝试使用Regex for .Net
获取带有命名组的网址的一部分示例
/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)
这意味着我错过了一些可选的东西?:(),但我似乎无法看到哪里,想想我有一天有太多的正则表达式:)
如果有人能帮助我,我们将不胜感激。
答案 0 :(得分: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)/)?)?
$
答案 1 :(得分: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 /”,因为这是从下一个(不可用)组中获得的。