Home > other >  How can i find the first index of date and time in string in Java
How can i find the first index of date and time in string in Java

Time:10-06

I have this string with YYYY-MM-DD HH:MM:SS date and time format as below:

String JAVA_STACK_TRACE = "ABC-007: This is a dummy ABC error message. This message can have multiple sentences." " 2021-09-24 19:12:50,672 Exception in thread \"main\" java.lang.RuntimeException: A test exception" " at com.stackify.stacktrace.StackTraceExample.methodB(StackTraceExample.java:13)" " at com.stackify.stacktrace.StackTraceExample.methodA(StackTraceExample.java:9)" " at com.stackify.stacktrace.StackTraceExample.main(StackTraceExample.java:5)";

I want to extract "ABC-007: This is a dummy DCS error message." this part from the string and neglect all the exception stack trace.

I was thinking that if I get the index of the date, I can do a sub string from the index 0 to the index of date.

I am not good with regex so haven't tried anything. Thanks in advance.

CodePudding user response:

Assuming the timestamp be the correct marker, you could try stripping it off along with all following content:

String output = JAVA_STACK_TRACE.replaceAll("\\s \\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.*$", "");
System.out.println(output);

This prints:

ABC-007: This is a dummy ABC error message. This message can have multiple sentences.

CodePudding user response:

Tim Biegeleisen’s simple code seems to be the best to obtain your real goal: extract the message before the date.

Since you asked for the index of the date, for the sake of completeness I wanted to show you that a regular expression can be used for that too:

    Pattern p = Pattern.compile("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3}");
    Matcher m = p.matcher(JAVA_STACK_TRACE);
    
    if (m.find()) {
        int indexOfDateAndTime = m.start();
        System.out.println("Index: "   indexOfDateAndTime);
    } else {
        System.out.println("Not found");
    }

Output:

Index: 86

The start() method of Matcher gives you the index of where the match started, the first matched character. There is a corresponding end method giving us the offset after the last character matched.

It’s a detour if all you want is the message, though.

  •  Tags:  
  • java
  • Related