How to match duplicate words in a regular expression?
Solution:
Following example shows how to search duplicate words in a regular expression by using p.matcher() method and m.group() method of regex.Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[])
throws Exception {
String duplicatePattern = "\\b(\\w+) \\1\\b";
Pattern p = Pattern.compile(duplicatePattern);
int matches = 0;
String phrase = " this is a test ";
Matcher m = p.matcher(phrase);
String val = null;
while (m.find()) {
val = ":" + m.group() + ":";
matches++;
}
if(val>0)
System.out.println("The string
has matched with the pattern.");
else
System.out.println("The string
has not matched with the pattern.");
}
}
Result:
The above code sample will produce the following result.