Java tutorial
import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class MainClass { public static void main(String args[]) { String phrase = "a word word"; String duplicatePattern = "\\b(\\w+) \\1\\b"; Pattern p = null; try { p = Pattern.compile(duplicatePattern); } catch (PatternSyntaxException pex) { pex.printStackTrace(); System.exit(0); } // count the number of matches. int matches = 0; // get the matcher Matcher m = p.matcher(phrase); String val = null; // find all matching Strings while (m.find()) { val = ":" + m.group() + ":"; System.out.println(val); matches++; } } }