Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matcher doesn't return the matched regex, instead returns whole string in group(0) (Java)

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

apples

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

How should I go about this?

>Solution :

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’

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading