仅替换完全匹配

时间:2014-07-14 06:45:05

标签: java

我有一个String和一些类似的话,如下所示: -

String sentence = "I have @ty and @ty-1 and @ty-2 as a sentence";

当我说

sentence = sentence.replaceAll("@ty", "space");

输出如下: -

sentence = "I have space and space-1 and space-2 as a sentence";

但是所需的输出是

sentence = "I have space and @ty-1 and @ty-2 as a sentence";

我也试过

sentence = sentence.replaceAll("@ty\\b", "space");

即使这样也没有给出正确的输出。

如何解决这个问题?

5 个答案:

答案 0 :(得分:2)

您正在尝试识别特殊字边界。正如你所说,你已经尝试过" \ b"正则表达式语法中内置的单词边界。不幸的是,这也将触发符号" @"和" - "。

似乎你只想在空间边界上工作。所以你必须自己写。用那个表达式:

sentence = sentence.replaceAll("(?<=\\s+)@ty(?=\\s+)", "space");

说明:部件(?<=\\s+)称为正向后视,仅查找空格。部分(?=\\s+)称为正向前瞻。这些外观尝试匹配字符而不消耗它们,因此您可以轻松地使用表达式来仅替换&#34; @ ty&#34;部分与你想要的&#34;空间&#34;。

有关详细信息,请查看此regex tutorial about lookarounds

答案 1 :(得分:2)

这是我的正则表达式:

@ty(?= |$)

这使用了一个超前表达式。它意味着&#34; @ty后跟一个空格或字符串的结尾&#34;。我使用以下测试字符串和&#34; g&#34;在此网站http://regex101.com/上测试了正则表达式。改性剂:

&#34;我有@ty和@ ty-1以及@ ty-2作为句子@ ty&#34;

答案 2 :(得分:1)

如果我理解了您的问题,您想要转义@符号并确保下一个字符是空格,然后您可以使用replaceAll()

String sentence = "I have @ty and @ty-1 and @ty-2 as a sentence";
sentence = sentence.replaceAll("\\@ty(\\s)", "space ");
System.out.println(sentence);

输出是指定的

I have space and @ty-1 and @ty-2 as a sentence

答案 3 :(得分:1)

您可以使用正则表达式:

sentence = sentence.replaceAll("@ty(?!\\-)", "space");

<强>解释
(?!\\-)是一个负面的预测,这意味着我们只关注@ty,后面没有短划线-

答案 4 :(得分:1)

为了完整起见,你也可以在不使用正则表达式的情况下做到这一点,但效率很低:

    String sentence = "I have @ty and @ty-1 and @ty-2 as a sentence";
    String []split = sentence.split("\\s");
    for (int i = 0; i < split.length; i++){
        if (split[i].equals("@ty")){
            split[i] = "space";
        }
    }

   sentence =  org.apache.commons.lang.StringUtils.join(split, " ");
   System.out.println(sentence);