0

I'm attempting to do the following:

            Scanner scanner = new Scanner(file);
            StringBuilder sb = new StringBuilder();
            while (scanner.hasNextLine()) {
                sb.append(scanner.nextLine() + "\n");
            }

            String data = sb.toString();

            Pattern p = Pattern.compile("\b[ABD-Z]*C[ABD-Z]*\b");
            Matcher m = p.matcher(data);

            String a = m.group();

How do I access the results of m? Why is my RegEx not working?

I have tried escaping backslashes already.

It works on http://www.gskinner.com/RegExr/ but I can't get any output from Java.

Please help≥.. thanks.

3
  • My RegEx is designed to extract strings with one C in it. Commented Jan 20, 2011 at 16:26
  • This is already the third posting today for the same homework. You need to write \\b instead of \b unless you mean the backspace character. Commented Jan 20, 2011 at 16:29
  • Yes, embarrasing,... I guess I after spending a long time experimenting I just got annoyed. I still have plenty more work, but I won't use SO for it. Just needed a starter for 10. : ) Commented Jan 20, 2011 at 17:24

3 Answers 3

1

You need to use m.find() or m.match() most likely in a while loop.

while (m.find()) {
 do something with m.group()
}
Sign up to request clarification or add additional context in comments.

Comments

1

yes you have to escape your backslashes to have a valid java string

you have to call m.find() before m.group()

2 Comments

Ok and how do I deal with multiple results?
as proposed by josh.trow simply loop until m.find() returns false
1

You need to use \\b instead of \b since the latter is a backspace and call m.find() if you're trying to match a substring or m.match() to match the whole string before calling group().

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.