Reputation: 1407
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
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
Upvotes: 41
Views: 76159
Reputation: 22973
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
Upvotes: 19
Reputation: 174696
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.
Upvotes: 14
Reputation: 771
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
Upvotes: 2
Reputation: 7071
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
Upvotes: 3
Reputation: 8202
You can use \b
to define the word boundary, so \baxe\b
in this case.
x = x.replaceAll("\\baxe\\b");
Upvotes: 2
Reputation: 2357
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.
Upvotes: 60