Skip to content

Instantly share code, notes, and snippets.

@iGabyTM
Last active March 8, 2023 02:31
Show Gist options
  • Save iGabyTM/7415263c2209653ede82457c289de697 to your computer and use it in GitHub Desktop.
Save iGabyTM/7415263c2209653ede82457c289de697 to your computer and use it in GitHub Desktop.
Hex color util for minecraft 1.16 and above

A simple util method for coloring strings using normal chat colors (&) and the new HEX colors added on 1.16, the format used it's <#FFFFFF> or <color_name> (second has a limited list of colors added into Bungeecord Chat API for the old color system, for example <red> it's &c).

A small visualization of how the regex works, made using debuggex.com
If this doesn't work go to debuggex.com and paste the pattern in there

import net.md_5.bungee.api.ChatColor;
import org.apache.commons.lang.StringUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HexUtil {
private static final Pattern PATTERN = Pattern.compile(
"<(#[a-f0-9]{6}|aqua|black|blue|dark_(aqua|blue|gray|green|purple|red)|gray|gold|green|light_purple|red|white|yellow)>",
Pattern.CASE_INSENSITIVE
);
public static String color(String text) {
if (text == null || text.isEmpty()) {
return "";
}
final Matcher matcher = PATTERN.matcher(text);
while (matcher.find()) {
try {
final ChatColor chatColor = ChatColor.of(matcher.group(1));
if (chatColor != null) {
text = StringUtils.replace(text, matcher.group(), chatColor.toString());
}
} catch (IllegalArgumentException ignored) { }
}
return ChatColor.translateAlternateColorCodes('&', text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment