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
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
Some other answers suggest you to use \\b
word boundaries to match an exact word. But \\bfoo\\b
would match the substring foo
in .foo.
. If you don't want this type of behavior then you may consider using lookaround based regex.
System.out.println(string.replaceAll("(?<!\\S)axe(?!\\S)", "sword"));
Explanation:
(?<!\\S)
Negative lookbehind which asserts that the match won't be preceded by a non-space character. i.e. the match must be preceded by start of the line boundary or a space.
(?!\\S)
Negative lookahead which asserts that the match won't be followed by a non-space character, i.e. the match must be followed by end of the line boundary or space. We can't use (?<=^|\\s)axe(?=\\s|$)
since Java doesn't support variable length lookbehind assertions.
DEMO
Include the word boundary before and after the word you want to replace.
String x = "axe pickaxe axe";
x = x.replaceAll("\\baxe\\b", "sword");
System.out.print(x);
edit output
sword pickaxe sword
You can use \b
to define the word boundary, so \baxe\b
in this case.
x = x.replaceAll("\\baxe\\b");
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.
If you only want to replace the first occurrence, there is a method replaceFirst
in String
object.
String x = "axe pickaxe";
x = x.replaceFirst("axe", "sword");
System.out.print(x); //returns sword pickaxe