Finding Duplicate Words

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Finding Duplicate Words

This Java example programdemonstrate how to find duplicate words.

[edit] Java Source Code

  • Package: example.validation
  • File: MatchDuplicateWords.java
package example.validation;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
 
public class MatchDuplicateWords {
    public static void main(String args[]) {
 
	hasDuplicate("pizza pizza");
	hasDuplicate("Faster pussycat kill kill");
	hasDuplicate("The mayor of of simpleton");
	hasDuplicate("Never Never Never Never Never");
	hasDuplicate("222 2222");
	hasDuplicate("sara sarah");
	hasDuplicate("Faster pussycat kill, kill");
	hasDuplicate(". .");
    }
 
    public static boolean hasDuplicate(String phrase) {
	boolean retval = false;
	String duplicatePattern = "\\b(\\w+) \\1\\b";
	Pattern p = null;
	try {
	    p = Pattern.compile(duplicatePattern);
	} catch (PatternSyntaxException pex) {
	    pex.printStackTrace();
	    System.exit(0);
	}
	int matches = 0;
	Matcher m = p.matcher(phrase);
	String val = null;
 
	while (m.find()) {
	    retval = true;
	    val = ":" + m.group() + ":";
	    System.out.println(val);
	    matches++;
	}
 
	String msg = "   NO MATCH: pattern:" + phrase + "\r\n             regex: " + duplicatePattern;
 
	if (retval) {
	    msg = " MATCH     : pattern:" + phrase + "\r\n         regex: " + duplicatePattern;
	}
 
	System.out.println(msg + "\r\n");
	return retval;
    }
}

[edit] What Result You Can Get

Run the program, you will get:

:pizza pizza:
 MATCH     : pattern:pizza pizza
         regex: \b(\w+) \1\b

:kill kill:
 MATCH     : pattern:Faster pussycat kill kill
         regex: \b(\w+) \1\b

:of of:
 MATCH     : pattern:The mayor of of simpleton
         regex: \b(\w+) \1\b

:Never Never:
:Never Never:
 MATCH     : pattern:Never Never Never Never Never
         regex: \b(\w+) \1\b

   NO MATCH: pattern:222 2222
             regex: \b(\w+) \1\b

   NO MATCH: pattern:sara sarah
             regex: \b(\w+) \1\b

   NO MATCH: pattern:Faster pussycat kill, kill
             regex: \b(\w+) \1\b

   NO MATCH: pattern:. .
             regex: \b(\w+) \1\b

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.


[edit] How to Run this Java Example Program

We recommend running this Java example program with Eclipse.

For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.

It's fairly easy.



[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools