如果关键短语是一个独立的单词,我该如何替换它?

时间:2017-06-25 17:31:56

标签: java string replace replaceall

例如,如果我要制作关键短语" ball",那么我需要一个句子"他因为正在打棒球而接球#34;到了#34;他抓住了XXXX,因为他正在打棒球"。相反,我得到了"他抓住了XXXX,因为他正在玩baseXXXX"。我正在使用replaceAll,这就是我收到此错误的原因,但我想知道是否有办法让我检查之后是否有空白字符,以及如果有空格或特殊字符,则只替换该单词。我挣扎的原因是因为如果跟着一个特殊的字符,而不是一个字母,我仍然想要替换这个词。

2 个答案:

答案 0 :(得分:4)

你可以使用boundary matcher(注意你必须逃避反斜杠)。边界\b一词也处理标点符号:

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"));

打印:

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

答案 1 :(得分:0)

试试这个:

    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));

输出:He caught the XXXX because he was playing baseball

修改

    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));

输出:!XXXX! ?ball1 XXXX! ball1 XXXX, 1ball1 baseball ba.ll

希望它有所帮助!