Java - String replace exact word

前端 未结 6 1195
难免孤独
难免孤独 2020-12-14 07:26
String x = \"axe pickaxe\";
x = x.replace(\"axe\", \"sword\");
System.out.print(x);

By this code, I am trying to replace the exact word axe

6条回答
  •  一整个雨季
    2020-12-14 07:53

    System.out.println("axe pickaxe".replaceAll("\\baxe\\b", "sword"));
    

    You need to use replaceAll instead of replace - because it can work with regular expressions. Then use the meta character \b which is for word boundary. In order to use it you need to escape the \ as double \ so the reges become \\baxe\\b

提交回复
热议问题