Christopher Miller Christopher Miller - 8 days ago 5
Java Question

Using replaceAll to ignore plurals, capitals, and punctuation?

I'm trying to make a program that replaces words in this sentence I made up with whatever the user wants the word to be replaced with:


"The duck quacked at the ducks dancing. Happy ducks! Sad Ducks!"


But, the problem is in I don't know how to replace the versions of duck with capitals, plurals, punctuation (duck, ducks, ducks!, Ducks!, etc)

I currently have this version but all it does is replace "duck", I'm not sure how to do the other variations.

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);

String story = "The duck quacked at the ducks dancing. Happy ducks! Sad Ducks!";

System.out.println("What word do you want replaced?");
String replaceWord = keyboard.nextLine();

story = story.replaceAll("\\bduck\\b", replaceWord);

System.out.println(story);
}

Answer

Using replaceAll to ignore plurals, capitals, and punctuation?

You have already managed punctuation well by surrounding the pattern with \\b.

To ignore capitals (ignore case), you can prefix the pattern with (?i), like this:

story = story.replaceAll("(?i)\\bduck\\b", replaceWord);

To handle plurals... That's language specific, and typically very irregular. If you want to handle something like that, then you will need a dictionary of singular and plural forms. Even then, there may be false negatives of some exceptional words.