Spring @RequestMapping“不包含”正则表达式

Add*_*ddJ 2 java regex spring request-mapping

我有这个请求映射:

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

我想添加 RequestMapping:

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

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

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

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

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

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

Wik*_*żew 6

您可以使用

"/route/to-{destination:(?!.*-from-).+}.html"
Run Code Online (Sandbox Code Playgroud)

锚点^将搜索字符串的开头,并且此处的任何匹配都会失败。

负向先行将使任何包含除换行符之外的 0+ 个字符之后的(?!.*-from-)输入失败。-from-

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