【问题标题】:Why this regex pattern matching does not work为什么这个正则表达式模式匹配不起作用
【发布时间】:2016-12-20 16:22:55
【问题描述】:

我正在使用 JPA 规范实现 RESTful 查询。想要处理具有多个条件的 url,如下所示:

http://localhost:8080/samples?search=lastName:doe,age>25

搜索字符串将匹配由“,”分隔的模式(\\w+?)(:|<|>)(\\w+?)

因此,我编写了以下代码来从字符串中获取 Matcher:

static Matcher getMatcherFromString(String str) {                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
    Pattern pattern = Pattern.compile("(\\w+?)(:|<|>)(\\w+?),");
    Matcher matcher = pattern.matcher(str + ",");
    return matcher;
}

然后在控制器中调用此方法来解析 url。

但是,当我使用字符串 analysisId:fdebfd6e-d046-4192-8b97-ac9f65dc2009 测试该方法时,它返回 null。为什么我的模式匹配做错了?

【问题讨论】:

  • 我会说因为\w 不匹配-
  • @Fallenhero \w 用于文字。我应该改用什么?
  • 我不知道你喜欢匹配什么,但也许[0-9a-zA-Z_-]
  • 或更简单(如果支持)[\w-]
  • @Fallenhero 尝试了 ([a-zA-Z_-])(:|&lt;|&gt;)([0-9a-zA-Z_-])([\w-])(:|&lt;|&gt;)([\w-]) 仍然无法正常工作。我认为个人模式很好。是匹配器组不起作用。

标签: regex rest jpa pattern-matching matcher


【解决方案1】:

我得到了这个工作: (\w+?)(:|)[a-zA-Z0-9\-]*,

我用这个来解决这个问题:https://regex101.com/r/fOEzd9/1

我认为主要问题是数字使 \w 与单词不匹配。您还需要考虑破折号。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,我用这个字符串解决了:

    "(\\w+?)(:|<|>)(\\w+?),"
    

    【讨论】:

      猜你喜欢
      • 2011-04-01
      • 2018-06-02
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多