Java Regex matching between curly braces

I need to parse a log file and get the times and associated function call string This is stored in the log file as so: {"time" : "2012-09-24T03:08:50", "message" : "Call() started"}

There will be multiple logged time function calls in between other string characters, so hence I am hoping to use regex to go through the file and grab all of these

I would like to grab the entire logged information including the curly brackets

I have tried the following

Pattern logEntry = Pattern.compile("{(.*?)}");
Matcher matchPattern = logEntry.matcher(file);

and

Pattern.compile("{[^{}]*}");
Matcher matchPattern = logEntry.matcher(file);

I keep getting illegal repetition errors, please help! Thanks.


Solution 1:

you need to escape '{' & '}' with a '\'

so: "{(.*?)}" becomes: "\\{(.*?)\\}"

where you have to escape the '\' with another '\' first

see: http://www.regular-expressions.info/reference.html for a comprehensive list of characters that need escaping...

Solution 2:

Braces are special regex characters used for repetition groups, therefore you must escape them.

Pattern logEntry = Pattern.compile("\\{(.*?)\\}");

Simple tester:

 public static void main(String[] args) throws Exception {
        String x =  "{\"time\" : \"2012-09-24T03:08:50\", \"message\" : \"Call() started\"}";
        Pattern logEntry = Pattern.compile("\\{(.*?)\\}");
        Matcher matchPattern = logEntry.matcher(x);

        while(matchPattern.find()) {
            System.out.println(matchPattern.group(1));
        }

    }

Gives me:

"time" : "2012-09-24T03:08:50", "message" : "Call() started"

Solution 3:

You should use a positive lookahead and lookbehind:

(?<=\{)([^\}]+)(?=\})
  • (?<={) Matches everything followed by {
  • ([^}]+) Matches any string not containing }
  • (?={) Matches everything before {