【问题标题】:No Match Found Exception altough the right match is in the String [duplicate]尽管正确的匹配在字符串中,但没有找到匹配异常[重复]
【发布时间】:2019-02-01 13:56:03
【问题描述】:

我正在读取一个文件,其中每一行都包含正确的匹配项,我只想提取数据。我使用以下正则表达式"\"ms_played\":\\s\"(\\d*)\"" 得到"somedata", "ms_played": "0815", "somedata"

我尝试了多个正则表达式在线测试,每个测试都找到匹配项,但我的代码没有。

long timeplayed = 0;
Pattern endTimePattern = Pattern.compile("\"ms_played\":\\s\"(\\d*)\"");
try (BufferedReader br = new BufferedReader(new FileReader("EndSong_.json"))) {
      String line = null;
      br.readLine();
      while ((line = br.readLine()) != null) {
            String endtime = endTimePattern.matcher(line).group(1);
            timeplayed += Long.parseLong(endtime);
      }
}

我的预期结果是提取包含 int 值的匹配器组 1。 我对 Java 端正则表达式比较陌生,如果有人能提供帮助,我将不胜感激。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您的正则表达式确实找到了第一个捕获组中的数字。但是你必须在 Matcher 上运行find()。然后就可以从中得到第一个捕获组了。

    例如:

    long timeplayed = 0;
    Pattern endTimePattern = Pattern.compile("\"ms_played\":\\s\"(\\d*)\"");
    String line = "\"somedata\", \"ms_played\": \"0815\", \"somedata\"";
    Matcher matcher = endTimePattern.matcher(line);
    matcher.find();
    timeplayed += Long.parseLong(matcher.group(1));
    System.out.println(timeplayed); // 815
    

    Exampe in Java | Regex

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多