使用正则表达式获取多个属性和值

时间:2015-11-26 00:22:15

标签: c# regex

我正在尝试在 $ filter 内的odata网址中获得一对 Property Value ,所以我有这个URL

  

/的OData / TopSellingItem?$扩大=项目,项目($选择=名称),科,科($选择=名称,$滤波器= A   NE   ' B')及$滤波器=年+当量+ 2015 +和+月+当量+' 1'&安培; $选择=年,月,值

我希望得到结果

  • A' B'
  • 年份+当量+ 2015
  • 月+当量+' 1'

我试过

(?<=\$filter=)(.*?)(?=\&|\))

但我只抓获了

  • A&#39; B&#39;
  • 年份+当量+ 2015 +和+月+当量+&#39; 1&#39;

是否有类似于重新评估捕获的组的结果以找到另一组模式或任何其他最佳方式来实现我的目标

提前致谢

我准备了一个在线测试人员

https://regex101.com/r/jO6nU5/1

1 个答案:

答案 0 :(得分:1)

这看起来像是面试的家庭作业或脑筋急转弯,但我会咬人(Regex101):

\$filter=(.+?)(?:&|\)|(\+and\+))(?(2)([^&)]+))

然后提取组1和3.说明:

\$filter=(.+?)      -- match any character after `$filter` and put them into capture group 1
(?:&|\)|(\+and\+))  -- stop when you encounter `&`, `)` or `+and+`
                    -- if you stop at `+and+`, put that into capture group 2
(?(2)([^&)]+))      -- if capture group 2 participated in the match,
                    -- continue capturing until `&` or `)`

(?(condition)then|else)是有条件的:

  • 条件可以是先行(?(?=pattern)then|else),后视或其负面变体。
  • 也可以检查群组n是否参与了匹配(?(n)then|else),这是我们使用的。此处不需要else部分。

免责声明:此限制仅匹配1 +and+。例如,给定此字符串:

$filter=abc+and+213+and+1234

Group 1 = abc
Group 2 = +and+
Group 3 = 213+and+1234

我欢迎所有改善它的努力。

相关问题