Java-字符串替换确切的单词 [英] Java - String replace exact word
本文介绍了Java-字符串替换确切的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String x = "axe pickaxe";
x = x.replace("axe", "sword");
System.out.print(x);
通过此代码,我试图用 sword
替换确切的单词 axe
.但是,如果运行此命令,它会打印 sword picksword
,而我只想打印 sword pickaxe
,因为 pickaxe
是与 axe
,尽管其中包含它.我怎样才能解决这个问题?谢谢
By this code, I am trying to replace the exact word axe
with sword
. However, if I run this, it prints sword picksword
while I would like to print sword pickaxe
only, as pickaxe
is a different word from axe
although it contains it. How can I fix this? Thanks
推荐答案
使用正则表达式和字边界 <代码> \ b :
String s = "axe pickaxe";
System.out.println(s.replaceAll("\\baxe\\b", "sword"));
边界符号中的反斜杠必须转义,因此必须为双反斜杠.
The backslash from the boundary symbol must be escaped, hence the double-backslashes.
这篇关于Java-字符串替换确切的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文