1

I am reading a file in which each line contains the right match and I just want to extract the data. I used the following regex "\"ms_played\":\\s\"(\\d*)\"" to get "somedata", "ms_played": "0815", "somedata".

I tried multiple regex online test and every test finds a match but my code doesn't.

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);
      }
}

My expected result was to extract the matcher group 1 which contains an int value. I am relatively new to Java end regex and would be very grateful if anybody could help.

Rmahajan
  • 1,311
  • 1
  • 14
  • 23

1 Answers1

3

Your regex does find the digits in the first capturing group. But you have have to run find() on the Matcher. Then you can get the first capturing group from it.

For example:

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

The fourth bird
  • 154,723
  • 16
  • 55
  • 70