Spring @RequestMapping “Not Contains” Regex

我的梦境 提交于 2019-12-20 04:58:11

问题


I have this RequestMapping:

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

And I would like to add that RequestMapping:

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

So it can serve all the "without departure" routes. That, however, creates a conflict as a "/route/to-destination-from-departure" url actually match this second RequestMapping as well... Fair enough so my solution was to specify a regex:

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

So that RequestMapping will not match if "destination" contains "-from-".

And... it does not work! The url "/route/to-barcelona-from-paris.html" is succesfully served by the first RequestMapping but the url "/route/to-barcelona.html" is not served at all... What I am missing?

Notes: I would like not to use a java solution such as having a single "/route/to-{destination}" RequestMapping then checking if "destination" contains "-from-".. :) Also, I can't alter those routes because of SEO...


回答1:


You may use

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

The ^ anchor would search for the start of the string and will fail any match here.

The (?!.*-from-) negative lookahead will fail any input that contains -from- after any 0+ chars other than line break chars.

The .+ pattern will consume all 1 or more chars other than line break chars to the end of the line.




回答2:


try using this :->

{destination:^(?!from)+}

or

{destination:^((?!-from-).)+}



来源:https://stackoverflow.com/questions/52003857/spring-requestmapping-not-contains-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!