Java - String replace exact word

前端 未结 6 1194
难免孤独
难免孤独 2020-12-14 07:26
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

相关标签:
6条回答
  • 2020-12-14 07:53
    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

    0 讨论(0)
  • 2020-12-14 07:54

    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

    0 讨论(0)
  • 2020-12-14 07:59

    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
    
    0 讨论(0)
  • 2020-12-14 08:04

    You can use \b to define the word boundary, so \baxe\b in this case.

    x = x.replaceAll("\\baxe\\b");
    
    0 讨论(0)
  • 2020-12-14 08:08

    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.

    0 讨论(0)
  • 2020-12-14 08:08

    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
    
    0 讨论(0)
提交回复
热议问题