|
5 | 5 | import net.md_5.bungee.api.chat.TextComponent; |
6 | 6 | import org.jetbrains.annotations.NotNull; |
7 | 7 |
|
| 8 | +import java.util.regex.Matcher; |
| 9 | +import java.util.regex.Pattern; |
| 10 | + |
8 | 11 | public class ColorTranslator { |
9 | 12 |
|
10 | | - static public final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))"; |
| 13 | + private static final Pattern HEX_PATTERN = Pattern.compile("(&#[0-9a-fA-F]{6})"); |
| 14 | + public static final String WITH_DELIMITER = "((?<=%1$s)|(?=%1$s))"; |
11 | 15 |
|
12 | 16 | /** |
13 | 17 | * @param text The string of text to apply color/effects to |
14 | 18 | * @return Returns a string of text with color/effects applied |
15 | 19 | */ |
16 | 20 | public static String translateColorCodes(@NotNull String text){ |
17 | | - |
18 | | - String[] texts = text.split(String.format(WITH_DELIMITER, "&")); |
19 | | - |
20 | | - StringBuilder finalText = new StringBuilder(); |
21 | | - |
22 | | - for (int i = 0; i < texts.length; i++){ |
23 | | - if (texts[i].equalsIgnoreCase("&")){ |
24 | | - //get the next string |
25 | | - i++; |
26 | | - if (texts[i].charAt(0) == '#'){ |
27 | | - finalText.append(ChatColor.of(texts[i].substring(0, 7))).append(texts[i].substring(7)); |
28 | | - }else{ |
29 | | - finalText.append(ChatColor.translateAlternateColorCodes('&', "&" + texts[i])); |
30 | | - } |
31 | | - }else{ |
32 | | - finalText.append(texts[i]); |
33 | | - } |
| 21 | + //good thing we're stuck on java 8, which means we can't use this (: |
| 22 | + // String hexColored = HEX_PATTERN.matcher(text) |
| 23 | + // .replaceAll(match -> "" + ChatColor.of(match.group(1))); |
| 24 | + Matcher matcher = HEX_PATTERN.matcher(text); |
| 25 | + StringBuffer sb = new StringBuffer(); |
| 26 | + while (matcher.find()) { |
| 27 | + String hex = matcher.group(1).substring(1); |
| 28 | + matcher.appendReplacement(sb, "" + ChatColor.of(hex)); |
34 | 29 | } |
| 30 | + matcher.appendTail(sb); |
| 31 | + |
| 32 | + String hexColored = sb.toString(); |
35 | 33 |
|
36 | | - return finalText.toString(); |
| 34 | + return ChatColor.translateAlternateColorCodes('&', hexColored); |
37 | 35 | } |
38 | 36 |
|
39 | 37 | /** |
|
0 commit comments