简体   繁体   中英

Java - String replace exact word

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

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.

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

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. ie 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, ie 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

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

您可以使用\\b来定义单词边界,因此在这种情况下为\\baxe\\b

x = x.replaceAll("\\baxe\\b");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM