Java – String replace exact word

Use a regex with word boundaries \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.

Leave a Comment