Search code examples
javastring-parsing

Extract the string from string in Java


I have this string in Java:

String str = "-High Upload Observed|High| eventId=285475664495 MMTT type=2  mrt=1482650158658 in=104858769 out=104858769 sessionId=0 generatorID=3+ACVIFkBABCAA951mZ0UyA\=\= modelConfidence=0 severity=0";

From the above string I need output be like

eventId=285475664495 MMTT 
type=2 
mrt=1482650158658
in=104858769 
out=104858769 
sessionId=0 
generatorID=3+ACVIFkBABCAA951mZ0UyA\=\= 
modelConfidence=0 
severity=0

Solution

  • Split the string into array by |, get the third element and remove everything after last space;

    String s = "Office|High| eventId=285469322819 MMTT type=2";
    s = s.split("\\|")[2].trim().replaceAll("[^ ]*$", "").trim();
    

    EDIT:

    Based on what OP given in the comment and assuming 'type` is always the third word.

    str = str.split("\\|")[2].replaceAll("type.*", "").trim() ;
    

    EDIT 2: Requirement changed again:

    String str = "-High Upload Observed|High| eventId=285475664495 MMTT type=2 mrt=1482650158658 in=104858769 out=104858769 sessionId=0 generatorID=3+ACVIFkBABCAA951mZ0UyA\\=\\= modelConfidence=0 severity=0\" output : eventId=285475664495 MMTT type=2 mrt=1482650158658 in=104858769 out=104858769 sessionId=0 generatorID=3+ACVIFkBABCAA951mZ0UyA\\=\\= modelConfidence=0 severity=0";
    Pattern p = Pattern.compile("[^ ]+=[^ ]+");
    Matcher m = p.matcher(str.split("\"")[0]);
    while (m.find()) {
        System.out.println(m.group());
    }
    

    produces:

    eventId=285475664495
    type=2
    mrt=1482650158658
    in=104858769
    out=104858769
    sessionId=0
    generatorID=3+ACVIFkBABCAA951mZ0UyA\=\=
    modelConfidence=0
    severity=0
    

    I admit MMTT is missing in the first one, but oh well.