gpt4 book ai didi

java - 仅替换完全匹配

转载 作者:行者123 更新时间:2023-12-02 14:45:13 25 4
gpt4 key购买 nike

我有一个字符串和一些类似的单词,如下所示:-

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

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

如何解决这个问题?

最佳答案

您可以使用正则表达式:

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

说明:
(?!\\-) 是一个否定的前瞻,这意味着我们只查找 @ty ,后面没有破折号 -.

关于java - 仅替换完全匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24730871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com