1

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.

5
  • please define under which criteria you want to get this result Commented Nov 18, 2011 at 10:57
  • 1
    Not enough details. Do you want to get the 3rd word of your string? Or what is always contained in "Breakpoint 10, * at file.c:10"? Or anything else? Commented Nov 18, 2011 at 10:57
  • Do you want to find the exact string 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). Commented Nov 18, 2011 at 10:58
  • @Guillaume yes, 3rd word of the string.. Commented Nov 18, 2011 at 11:00
  • I'd suggest a Tokenizer, then, see my answer Commented Nov 18, 2011 at 11:01

6 Answers 6

4

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 ().

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

1
  1. Good website regular-expressions.info
  2. Good online tester regexpal.com
  3. Java http://download.oracle.com/javase/tutorial/essential/regex/

I turn to these when I want to play with Regex

Comments

1

Have you seen the standard Sun tutorial on regular expressions ? In particular the section on matching groups would be of use.

Comments

0

Try: .*Breakpoint \d+, (.*) at

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.