Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - String replace exact word

Tags:

java

string

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

like image 452
Oti Na Nai Avatar asked May 12 '15 06:05

Oti Na Nai


People also ask

How do you replace a word in a string in Java without using replace method?

To replace a character in a String, without using the replace() method, try the below logic. Let's say the following is our string. int pos = 7; char rep = 'p'; String res = str. substring(0, pos) + rep + str.

How do I remove part of a string?

You can also remove a specified character or substring from a string by calling the String. Replace(String, String) method and specifying an empty string (String. Empty) as the replacement. The following example removes all commas from a string.


1 Answers

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.

like image 111
hiergiltdiestfu Avatar answered Sep 23 '22 17:09

hiergiltdiestfu