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.
To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.
format (also used by VF apex:outputtext ) uses the Java MessageFormat class. And braces are escaped by enclosing in single quotes, which in apex must also be escaped by backslash.
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.
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...
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With