简体   繁体   中英

How to parse given string using regular expression in java

Given String:

<180>May 19 17:54:27 ise121 CISE_Internal_Operations_Diagnostics 0000046406 2 0 2015-05-19 17:54:27.930 +05:30 0000290168 34126 WARN  System-Management: Remote syslog target is unavailable

My RegEx :

\\<(\\d+)\\>(\\w+[\\d\\s\\:]+\\S+\\s\\S+\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s([\\d\\:\\-\\.\\+\\s]{0,30})\\s+\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\S+\\:.*?\\,)(.*)

but this is not working so please help

Code:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatchMoreLogsFromSingleRegEx {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = "<180>May 19 17:54:27 ise121 CISE_Internal_Operations_Diagnostics 0000046406 2 0 2015-05-19 17:54:27.930 +05:30 0000290168 34126 WARN  System-Management: Remote syslog target is unavailable";

        Pattern pattern = Pattern
                .compile("\\<(\\d+)\\>(\\w+[\\d\\s\\:]+\\S+\\s\\S+\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s([\\d\\:\\-\\.\\+\\s]{0,30})\\s+\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\S+\\:.*?\\,)(.*)");

        Matcher matcher = pattern.matcher(s);
        if (matcher.find()) {
            System.out.println("true");
            StringBuilder sb = new StringBuilder();
            int cnt = matcher.groupCount();
            System.out.println(cnt);
            for (int i = 1; i <= cnt; ++i) {
                System.out.println(matcher.group(i) + "\t" + i);
            }

        } else {
            System.out.println("false");
        }
    }
}

It fails to work because there isn't a comma exists after the substring System Management: . So remove the last comma.

\\<(\\d+)\\>(\\w+[\\d\\s\\:]+\\S+\\s\\S+\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s([\\d\\:\\-\\.\\+\\s]{0,30})\\s+\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(\\S+\\:.*?)(.*)

DEMO

I think you want something like this. Here I made the comma part as optional.

\<(\d+)\>(\w+[\d\s\:]+\S+\s\S+\s(\d+)\s(\d+)\s(\d+)\s([\d\:\-\.\+\s]{0,30})\s+\d+)\s+(\d+)\s+(\S+)\s+(\S+\:(?:.*?,)?)(.*)

Escape the backslash one more time in java.

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM