-1

I'm working on a system there connect my website with my Minecraft Server through a JavaPlugin! But I had meet some problem when I try to replace $player in a String with my Minecraft Players Ing Name, please help :)

ResultSet results = statement.executeQuery();
if(results.next()) {
    String command = ""+results.getString(2);
    String newcmd = ""+command.replaceAll("\b$player\b", ""+player.getName());
    System.out.println(newcmd);
    player.sendMessage("\u00A75SpaceStore \u00A78\u00A7l| \u00A72Code Activated!");
}

String command is the same as "give $player stone"

Output

give $player stone

1 Answers1

0

First, you need to use double backslashes to specify the word boundary as stated in Backslashes, escapes, and quoting here: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler.

Second, there's no word boundary between the space and $ symbol as they are both non-word symbols, you can read the explanation of the word boundary here: What is a word boundary in regexes?

The proper syntax will be System.out.println(s.replaceAll("\\$player\\b", "user1"));

Try this code:

public static void main(String[] args) {
  String s = "give $player stone";
  System.out.println(s.replaceAll("\\b\\$player\\b", "user1"));
  System.out.println(s.replaceAll("\\$player\\b", "user1"));
}

It outputs:

give $player stone
give user1 stone
egor10_4
  • 331
  • 2
  • 9