【问题标题】:Java regex to accept either UUID or only numbers in URL patternJava 正则表达式接受 UUID 或仅接受 URL 模式中的数字
【发布时间】:2019-02-26 06:09:01
【问题描述】:

我在 Spring Boot 中添加多个 http 安全性并添加基于 URL 模式的过滤器。我有一个端点 /abc/{id},它接受​​查询参数作为 id,可以是 UUID 或数字。我正在尝试创建一个正则表达式模式,它可以接受 UUID 或仅接受数字,例如 http.regexpattern(“/abc/”).authorzerequest()。我尝试使用管道运算符(或在正则表达式中),但它在这里不起作用。 我不想添加两种不同的 http 安全配置,一种用于 uuid,另一种用于数字。 可以在 http 中工作的正则表达式模式是什么? 这是带有 regex OR operator(Pipe |) 的代码,它不起作用”

protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.regexMatcher("/abc/([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})|([0-9]+$)").authorizeRequests()
                .anyRequest().authenticated().and().addFilterBefore(new CustomFilter(), BasicAuthenticationFilter.class);

        http.addFilterAfter(new EnvironmentFilter(jwtTokenUtility), BasicAuthenticationFilter.class);

}

【问题讨论】:

  • 您能否与一些示例字符串分享您的代码,其中包含实际结果与预期结果?
  • 我想通了。不确定 spring 是如何解释模式的,但它通过恢复 OR 运算符 http.regexMatcher("/abc/([0-9]+$)|([0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})").authorizeRequests() .anyRequest().authenticated().and().addFilterBefore(new CustomFilter(), BasicAuthenticationFilter.class); 周围的模式来工作

标签: java regex spring-boot spring-security


【解决方案1】:

不知道Spring有没有自己的正则表达式风格,但是如果你能知道它是什么风格的正则表达式,你可以使用https://regex101.com/,这是一个非常好的正则表达式测试环境。

不知道 Spring,Java 有它自己的正则表达式风格,据我所知,它包含管道运算符 OR 并且效果很好。举个例子:

// example input
String input0 = "MyPatteRn"; // matches
String input1 = "myPattern"; // matches
String input2 = "MypaTTern"; // no match

Pattern pattern = Pattern.compile("my|My(Patt|PaTT)e(?:r|R)n");
Matcher matcher = pattern.matcher(inputSequence);
if (matcher.matched()) {
    String patt = matcher.group(1);
}

【讨论】:

    猜你喜欢
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2023-03-24
    • 2017-11-16
    相关资源
    最近更新 更多