Java Stack Trace RegEx

by Tim Cull

This is just a quick post because it’s been a while and I wanted to save others from the pain I experienced yesterday.

If you want to parse a Java stack trace with a regular expression and pull out the class name, method name, and line number, then you can use this code below:

Pattern pattern = Pattern.compile("([a-zA-Z0-9_\\.]*)\\.([a-zA-Z0-9_\\.]*)\\([a-zA-Z0-9_\\.]*:([\\d]*)\\)");
Matcher matcher = pattern.matcher(traceString);
while (matcher.find()){
    String className = matcher.group(1);
    String methodName = matcher.group(2);
    int lineNumber = Integer.parseInt(matcher.group(3) == null ? "0" : matcher.group(3));
}

Note that because you are passing a Java string into a regular expression, you have to double-escape many of those characters. For example, if you want to say “any decimal” the usual regular expression is “\d” but because you are using a Java string to define the regular expression you have to double escape it to say “\\d” instead.

I’d like to give some props to David Matuszek whose nifty online Regular Expression Test Applet made debugging this hairy thing much easier.

Bookmark and Share

2 Comments to “Java Stack Trace RegEx”

  1. Thanks! This helped me a lot

Leave a Reply