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".
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