Search code examples
javastringreplacereplaceall

How do I replace a key phrase only if it is a standalone word?


For example, if I were to make the keyphrase "ball", then I would need the sentence "He caught the ball because he was playing baseball" to "He caught the XXXX because he was playing baseball". Instead, I'm getting "He caught the XXXX because he was playing baseXXXX". I'm using replaceAll, which is why I'm getting this error, but I was wondering if there is a way for me to check if there's a character that isn't whitespace afterwards, and only replace the word if there is either whitespace or special characters. The reason I'm struggling is because I still want the word to replaced if it is followed by a special character, but not a letter.


Solution

  • You can use a boundary matcher (note that you have to escape the backslash). The word boundary \b also takes care of punctuation marks:

    System.out.println("He caught the ball because he was playing baseball"
                .replaceAll("\\bball\\b", "XXXX"));
    System.out.println("One ball, two cats. Two cats with a ball."
                .replaceAll("\\bball\\b", "XXXX"));
    System.out.println("A ball? A ball!".replaceAll("\\bball\\b", "XXXX"));
    

    Prints:

    He caught the XXXX because he was playing baseball
    One XXXX, two cats. Two cats with a XXXX.
    A XXXX? A XXXX!