I can't find any good resource for parsing with regular expression. Could someone please show me the way.
How can I parse this statement?
"Breakpoint 10, main () at file.c:10"
I want get the substring "main ()" or 3rd word of the statement.
This works:
public void test1() {
String text = "Breakpoint 10, main () at file.c:10";
String regex = ",(.*) at";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
Basically the regular expression .(.*) at with group(1) returns the value main ().
Assuming you want the 3rd word of your string (as said in your comments), first break it using a StringTokenizer. That will allow you to specify separator (space is by default)
List<String> words = new ArrayList<String>();
String str = "Breakpoint 10, main () at file.c:10";
StringTokenizer st = new StringTokenizer(str); // space by default
while(st.hasMoreElements()){
words.add(st.nextToken());
}
String result = words.get(2);
That returns main
If you also want the (), as you defined spaces as separator, you also need to take the next word words.get(3)
I turn to these when I want to play with Regex
Have you seen the standard Sun tutorial on regular expressions ? In particular the section on matching groups would be of use.
main()or any method name that could possibly contain parameters as well? Anyways, regular-expressions.info has a good regex reference and quite some tutorials (even Java specific ones).