-1

The problem I'm facing is that upon following the question at this link, Using Regular Expressions to Extract a Value in Java, I am unable to extract the correct group of the String

Pattern p = Pattern.compile("I have .*");
Matcher m = p.matcher("I have apples");

if(m.find()){
    System.out.println(m.group(0));
}

What I get:

I have apples

What I want to get:

apples

I've tried asking for m.group(1) as well but it throws me an exception.

How should I go about this?

1 Answers1

3

You have to define a capturing group to get m.group(...) work correctly.

Change your pattern to

Pattern p = Pattern.compile("I have (.*)");

m.group(0) 'denotes the entire pattern' m.group(1) now returns the expected 'apple'

blafoo
  • 116
  • 7