I get string like
main.c:11: error: 'qz' undeclared (first use in this function)
like parameter to function. I need to use regex and split name of file ( main.c ), line (11) and message ( 'qz' undeclared (first use in this functi开发者_如何学JAVAon) ). I wrote regex like this
private static Pattern patern=Pattern.compile("([a-zA-Z0-9_-]+\.c:)([0-9]+:)(.)*");
but it doesn't split. Can anybody tell me what regex to use ?
You at least need to escape that \
. Try
"([a-zA-Z0-9_-]+\\.c:)([0-9]+:)(.)*"
instead.
Here is a demo:
import java.util.regex.*;
public class Test {
public static void main(String[] args) {
String input = "main.c:11: error: 'qz' undeclared (first use in this function)";
Pattern p = Pattern.compile("([^:]+\\.c):(\\d+):(.*)");
Matcher m = p.matcher(input);
if (m.matches()) {
System.out.println("File: " + m.group(1));
System.out.println("Line: " + m.group(2));
System.out.println("Message: " + m.group(3));
}
}
}
Prints:
File: main.c
Line: 11
Message: error: 'qz' undeclared (first use in this function)
Another option would just be to do input.split(":")
.
I'd do it like this:
^(.*?):(\d+):\s(error|warning):\s(.*?)
This will get you the filename as first result, the line number as second and the error message as the fourth match. Also, it captures warnings of the same format, too.
Edited to capture line number.
精彩评论