I've written a simple util-method in my spigot plugin to check if a message contains a valid minecraft colour code. A valid minecraft colour code consists of a &
followed by a hex digit: 0
to f
. Minecraft itself exchanges all &
by a §
, for reasons that would take too long to explain, it's not possible for the users to send messages to the server directly. Therefore &
is generally used as a replacement.
I now have to check at some point, if the message the user sent to the server is coloured, which is the reason this method exists. Here are some quick examples, how it does work:
string value - return value
"Simple String" - false
"Smith&Wesson" - false
"&4This would be red." - true
"%aGreen &2Darker Green &0 Darkest Green" - true
"&& Omega &&" - false
Here's my code. It does what it's supposed to do, but for some reason it still seems unneccesary clunky to me. Any improvement is welcome :)
public static boolean isMessageColoured(String message) {
char[] arr = message.toCharArray();
for (int i = 0; i < message.length() - 2; i++) {
if (arr[i] == '&' && "0123456789abcdef".contains(Character.toString(arr[i + 1]))) {
return true;
}
}
return false;
}