我有一个字符串和一些类似的单词,如下所示:
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
没有后跟破折号的地方-
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句