Java-read lines of files and extract only the helpfull info

后端 未结 1 1021
星月不相逢
星月不相逢 2021-01-28 14:50

I have files file1, file2 contains contents such:

[2017-02-01 10:00:00 start running [error:yes] [doing:no] [finish:] [remind:] [alarmno:123456789] [logno:12345678

相关标签:
1条回答
  • 2021-01-28 15:35

    You may use

    ^\[?(\d[\d-]+).*?\[alarmno:(\w*)].*?\[logno:(\w*)].*?\[type:\w*:([^\]]*)]
    

    See the regex demo

    Details:

    • ^ - start of string
    • \[? - an optional [
    • (\d[\d-]+) - Group 1: a digits and 1 or more digits or -s
    • .*? - any 0+ chars other than line break chars as few as possible
    • \[alarmno: - a [alarmno: substring
    • (\w*) - Group 2: 0+ word chars
    • ] - a literal ]
    • .*? - any 0+ chars other than line break chars as few as possible
    • \[logno: - a literal [logno: substring
    • (\w*) - Group 3: 0+ word chars
    • ] - a ]
    • .*? - any 0+ chars other than line break chars as few as possible
    • \[type: - a [type: substring
    • \w* - 0+ word chars
    • : - a colon
    • ([^\]]*) - Group 4: 0+ chars other than ]
    • ] - a ]

    Java demo:

    String s = "[2017-08-17 08:00:00 Comming in [Contact:NO] [REF:] [REF2:] [REF3:] [Name:+AA] [Fam:aa] [TEMP:-2:0:-2:0:-2] [Resident:9:free] [end:0:]";
    Pattern pat = Pattern.compile("^\\[*(\\d[\\d: -]+\\d).*?\\[Name:([^]]*)].*?\\[Fam:(\\w*)].*?\\[Resident:\\w*:([^]]*)]");
    Matcher matcher = pat.matcher(s);
    if (matcher.find()){
        System.out.println("Date: " + matcher.group(1));
        System.out.println("Name: " + matcher.group(2)); 
        System.out.println("Fam: " + matcher.group(3)); 
        System.out.println("Resident: " + matcher.group(4)); 
    } 
    

    Output:

    Date: 2017-08-17 08:00:00
    Name: +AA
    Fam: aa
    Resident: free
    
    0 讨论(0)
提交回复
热议问题