Java 弹簧控制器中的正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18422368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:30:45  来源:igfitidea点击:

Regex in spring controller

javaregexspringspring-mvcroutes

提问by zmanc

I am trying to build a request filter that will only get used if it matches a pattern of the letter e, then a number. However I cannot seem to get it to work. I keep getting 400 errors every time I try something with regex.

我正在尝试构建一个请求过滤器,只有当它匹配字母 e 和数字的模式时才会被使用。但是我似乎无法让它工作。每次尝试使用正则表达式时,我都会收到 400 个错误。

If I just use the following it "works" but also captures mappings that do not have numbers which I don't want.

如果我只使用以下它“有效”,但也会捕获没有我不想要的数字的映射。

@RequestMapping(value = "e{number}",
            method = RequestMethod.GET)

I have tried the following combinations.

我尝试了以下组合。

@RequestMapping(value = "e{number}",
            params = "number:\d+",
            method = RequestMethod.GET)

@RequestMapping(value = "e{number:\d+}",
            method = RequestMethod.GET)

@RequestMapping(value = "/e{^\+?\d+$}",
            method = RequestMethod.GET)

@RequestMapping(value = "/{^\e+?\d+$}",
            method = RequestMethod.GET)

采纳答案by sam

According to the documentation, you have to use something like {varName:regex}. There's even an example :

根据文档,您必须使用类似{varName:regex}. 甚至还有一个例子:

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}{extension:\.[a-z]+}")
  public void handle(@PathVariable String version, @PathVariable String extension) {
    // ...
  }
}

回答by Koen van Dijk

You should use:

你应该使用:

 @RequestMapping("/e{number:\d+})

Notice the "escaped slash" before the \ddigit specifier.

注意\d数字说明符之前的“转义斜线” 。