I am trying to use the replaceAll()
method to replace a everything on a string except a a string sequence but I don't make it work, I have the following code:
Basically:
String message = "§eTeste"
String color = message.replaceAll(?, ""); // The problem
System.out.println(color);
Output should be "§e"
Code:
String[] args = message.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
String teste = args[i].replaceAll("§[0-9A-Fa-fK-Rk-r]", "");
if (i == (args.length-1)) {
if (teste.matches("http://" + "(.*)") || teste.matches("https://" + "(.*)")) {
String cor = "";
if (!args[i].matches("(.*)" + "§[0-9A-Fa-fK-Rk-r]" + "(.*)") && (sb.toString() !=null) && !sb.toString().isEmpty()) {
cor = sb.toString().replaceAll("[^(§[0-9A-Fa-fK-Rk-r])]", "");
}
if ((sb.toString() !=null) && !sb.toString().isEmpty()) {
JSONObject objeto = new JSONObject();
objeto.put("text", sb.toString());
jmessage.add(objeto);
}
JSONObject objeto = new JSONObject();
JSONObject extra = new JSONObject();
extra.put("action", "open_url");
extra.put("value", teste);
objeto.put("text", cor + args[i]);
objeto.put("clickEvent", extra);
jmessage.add(objeto);
}
else {
JSONObject objeto = new JSONObject();
sb.append(args[i]);
objeto.put("text", sb.toString());
jmessage.add(objeto);
}
}
else {
if (teste.matches("http://" + "(.*)") || teste.matches("https://" + "(.*)")) {
String cor = "";
if (args[i].matches("(.*)" + "§[0-9A-Fa-fK-Rk-r]" + "(.*)")) {
cor = args[i].replaceAll("[^(§[0-9A-Fa-fK-Rk-r])]", "");
}
else if (sb.toString() !=null) {
cor = sb.toString().replaceAll("[^(§[0-9A-Fa-fK-Rk-r])]", "");
}
if ((sb.toString() !=null) && !sb.toString().isEmpty()) {
JSONObject objeto = new JSONObject();
objeto.put("text", sb.toString());
jmessage.add(objeto);
sb = new StringBuilder();
sb.append(" " + cor);
}
JSONObject objeto = new JSONObject();
JSONObject extra = new JSONObject();
objeto.put("text", cor + args[i]);
extra.put("action", "open_url");
extra.put("value", teste);
objeto.put("clickEvent", extra);
jmessage.add(objeto);
}
else {
sb.append(args[i] + " ");
}
}
}
jmessage is a JSONArray create out of the message that is a string input made by a sender (player/console)
The "§[0-9A-Fa-fK-Rk-r]" represents the color of the message, in this methot I am creating the JSONArray where the location of link has the click_event (every time a create a new "text" I need to send it the curret color)
I have found a solution... the replaceAll()
method can not separe more than 1 char.. because of this I have created this method to resolve the problem:
private String findCor(String string) {
char[] b = string.toCharArray();
StringBuilder sb = new StringBuilder();
sb.append("");
for (int i = 0; i < (b.length-1); i++) {
if ((b[i] == ChatColor.COLOR_CHAR) && ("0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[(i + 1)]) > -1)) {
sb.append(b[i]);
sb.append(b[(i + 1)]);
}
}
return sb.toString();
}