1

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.

Stephen Burns
  • 162
  • 2
  • 17

2 Answers2

4

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!
Marvin
  • 13,325
  • 3
  • 51
  • 57
0

Try this:

    String s = "He caught the ball because he was playing baseball";
    String replaceKey = "ball";
    String replaceValue = "XXXX";

    String[] sArray = s.split(" ");

    String finalS = "";
    for(int i=0; i<sArray.length;i++) {
        if(replaceKey.equals(sArray[i])){
            sArray[i] = replaceValue;
        }
    }

    System.out.println(String.join(" ", sArray));

OUTPUT: He caught the XXXX because he was playing baseball

EDIT:

    String s = "!ball! ?ball1 ball! ball1 ball, 1ball1 baseball ba.ll";
    String replaceKeyPattern = "^[\\W+[ball]\\W+]+$";
/*    \\W is all non word characters= special characters */

    String replaceKey = "ball";
    String replaceValue = "XXXX";

    String[] sArray = s.split(" ");

    String finalS = "";
    for(int i=0; i<sArray.length;i++) {
        if(sArray[i].matches(replaceKeyPattern)){
            sArray[i] = sArray[i].replace(replaceKey,replaceValue);
        }
    }

    System.out.println(String.join(" ", sArray));

OUTPUT:!XXXX! ?ball1 XXXX! ball1 XXXX, 1ball1 baseball ba.ll

Hope it helps!

Firoz Memon
  • 4,282
  • 3
  • 22
  • 32
  • 1
    What about the special characters as asked in OP: "I'm struggling is because I still want the word to replaced if it is followed by a special character, but not a letter." – Shailesh Saxena Jun 25 '17 at 17:54