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

Regex works using Java regex engine on regex101, but fails in Java code

I’m using this expression to capture the first duplicate word.

.*\b(\w+)\b.*\1.*

Regex101: https://regex101.com/r/774R0I/1

The string I’m testing is "this is a sentence with with a dup".

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

It works as intended on regex101 with Java 8’s engine. The entire string is matched and ‘with’ is captured.

When I use it in Java 8, I’m getting IllegalStateException: No match found.

Java snippet:

String regex = ".*\\b(\\w+)\\b.*\\1.*";
String sentence = "this is a sentence with          with a dup";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sentence);

System.out.println(matcher.group());

>Solution :

You need to call method find first. Refer to the javadoc, in particular the following sentence.

If the match succeeds then more information can be obtained via the start, end, and group methods.

In other words, you can’t call method group without first calling method find.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex101 {

    public static void main(String[] args) {
        String regex = ".*\\b(\\w+)\\b.*\\1.*";
        String sentence = "this is a sentence with          with a dup";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sentence);
        if (matcher.find()) {
            System.out.println(matcher.group(1));
        }
    }
}

Above code prints the following:

with
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