【问题标题】:Spring @RequestMapping "Not Contains" RegexSpring @RequestMapping“不包含”正则表达式
【发布时间】:2019-01-30 21:34:39
【问题描述】:

我有这个 RequestMapping:

@RequestMapping(value = "/route/to-{destination}-from-{departure}.html", method = {RequestMethod.GET, RequestMethod.HEAD})

我想添加那个 RequestMapping:

@RequestMapping(value = "/route/to-{destination}.html", method = {RequestMethod.GET, RequestMethod.HEAD})

因此它可以服务于所有“无出发”路线。但是,这会产生冲突,因为“/route/to-destination-from-departure”url 实际上也匹配第二个 RequestMapping ...... 很公平,所以我的解决方案是指定一个正则表达式:

@RequestMapping(value = "/route/to-{destination:^((?!-from-).)+}.html", method = {RequestMethod.GET, RequestMethod.HEAD})

如果“destination”包含“-from-”,则RequestMapping将不匹配。

而且...它不起作用!第一个 RequestMapping 成功提供了 URL“/route/to-barcelona-from-paris.html”,但根本没有提供 URL“/route/to-barcelona.html”......我错过了什么?

注意:我不想使用 java 解决方案,例如使用单个“/route/to-{destination}”RequestMapping 然后检查“destination”是否包含“-from-”.. :) 另外,我可以不要因为 SEO 而改变那些路线...

【问题讨论】:

  • 试试{destination:(?!.*-from-).+}.html{destination:(?!.*-from-)[^\/]+}.html
  • @WiktorStribiżew "{destination:(?!.*-from-).+}" 有效!你让我很开心,非常感谢! (“{destination:(?!.*-from-)[^\/]+}”没有)作为奖励,这里有一个关于你的片段哈哈:commitstrip.com/en/2014/02/24/coder-on-the-verge-of-extinction

标签: java regex spring request-mapping


【解决方案1】:

你可以使用

"/route/to-{destination:(?!.*-from-).+}.html"

^ 锚点将搜索字符串的开头,并将在此处匹配失败。

(?!.*-from-) 否定前瞻将使任何包含 -from- 的输入在除换行符之外的任何 0+ 字符之后失败。

.+ 模式将消耗除换行符之外的所有 1 个或多个字符到行尾。

【讨论】:

    【解决方案2】:

    尝试使用这个:->

    {目的地:^(?!from)+}

    {目的地:^((?!-from-).)+}

    【讨论】:

    • 两种都试过了,没用! Wiktor Stribiżew 的“{destination:(?!.*-from-).+}.html”虽然有效,但我们有解决方案!感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多