Skip to content

Commit cacbe61

Browse files
committed
Cleanup translateColorCodes
1 parent c3dec13 commit cacbe61

1 file changed

Lines changed: 17 additions & 19 deletions

File tree

src/main/java/me/kodysimpson/simpapi/colors/ColorTranslator.java

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,35 +5,33 @@
55
import net.md_5.bungee.api.chat.TextComponent;
66
import org.jetbrains.annotations.NotNull;
77

8+
import java.util.regex.Matcher;
9+
import java.util.regex.Pattern;
10+
811
public class ColorTranslator {
912

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))";
1115

1216
/**
1317
* @param text The string of text to apply color/effects to
1418
* @return Returns a string of text with color/effects applied
1519
*/
1620
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));
3429
}
30+
matcher.appendTail(sb);
31+
32+
String hexColored = sb.toString();
3533

36-
return finalText.toString();
34+
return ChatColor.translateAlternateColorCodes('&', hexColored);
3735
}
3836

3937
/**

0 commit comments

Comments
 (0)