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)
Have you seen the standard Sun tutorial on regular expressions ? In particular the section on matching groups would be of use.
I turn to these when I want to play with Regex
尝试: .*Breakpoint \\d+, (.*) at
Well, the regular expression main \\(\\)
does parse this. However, I suspect that you would like everything after the first comman and before the last "at": ,(.*) at
gives you that in group(1) that is opened by the parenthesis in the expression.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.