Java Regex matching between curly braces

后端 未结 5 698
说谎
说谎 2020-12-03 03:27

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\" : \"C

相关标签:
5条回答
  • 2020-12-03 03:57

    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...

    0 讨论(0)
  • 2020-12-03 04:05

    {} in regexp have special meaning, so they need to be escaped.

    Usually escaping is achieved by preceeding the character to be escaped with a backslash. In a character class defined with square brackets, you shouldn't need to do this

    So something like

    Pattern.compile("\{[^{}]*\}");
    

    Could be nearer to what you want to do

    0 讨论(0)
  • 2020-12-03 04:11

    This works perfectly for non-nested brackets but for expressions like

    (sum(x) * 100) / (sum(y) + sum(z))

    [a-z]*[\{]+([a-zA-Z0-9]+)[\}]+ works.

    0 讨论(0)
  • 2020-12-03 04:19

    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"
    
    0 讨论(0)
  • 2020-12-03 04:19

    You should use a positive lookahead and lookbehind:

    (?<=\{)([^\}]+)(?=\})
    
    • (?<={) Matches everything followed by {
    • ([^}]+) Matches any string not containing }
    • (?={) Matches everything before {
    0 讨论(0)
提交回复
热议问题