Java - String replace exact word -
string x = "axe pickaxe"; x = x.replace("axe", "sword"); system.out.print(x);
by code, trying replace exact word axe
sword
. however, if run this, prints sword picksword
while print sword pickaxe
only, pickaxe
different word axe
although contains it. how can fix this? thanks
use regex word boundaries \b
:
string s = "axe pickaxe"; system.out.println(s.replaceall("\\baxe\\b", "sword"));
the backslash boundary symbol must escaped, hence double-backslashes.
Comments
Post a Comment