1

我正在尝试制作一个 Minecraft Bukkit 插件,它涉及制作主题标签等。我有它,所以当你这样做时#hashtag-goes-here它会突出显示它。唯一的问题是,你必须在它后面加上另一个词(有一个空格)才能工作。到目前为止,这是我的代码:

            try{
                for(int i = index; i < message.length(); i++){
                    String str = Character.toString(message.charAt(i));
                    String sbString = sb.toString().trim();
                    System.out.println(sbString);
                    if(str.equals(" ")){
                        str.replace(str, str + ChatColor.RESET);
                        String hName = sb.toString().replaceFirst("#", "").trim();
                        String newMessage = message.replaceAll("#", ChatColor.AQUA + "#").replace(str, ChatColor.RESET + str);
                        event.setMessage(newMessage);
                        logHashtag(event.getPlayer(), event.getMessage(), hName);
                        break;
                    }else{
                        sb.append(str);
                    }
                }
            }catch(Exception e){
                throw new HashtagException("Failed to change hashtag colors in message!");
            }

编辑:(已经回答,去年,我知道;这是为了让阅读本文的人知道我在问什么)我的问题是,它可以在可以找到主题标签的所有情况下工作。感谢halfbit帮我 :)

4

2 回答 2

1

If you want to find strings in a text and highlight them, then regular expressions can be quite useful. You might use code similar to the following:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HashTagColorizer {

    public static void main(String[] args) {
        String AQUA = "<AQUA>", RESET = "<RESET>";
        String message = "Aaa #hashtag-goes-here bbb #another-hashtag ccc";
        Pattern pattern = Pattern.compile("#([A-Za-z0-9-]+)");
        Matcher matcher = pattern.matcher(message);
        StringBuilder sb = new StringBuilder(message.length());
        int position = 0;
        while (matcher.find(position)) {
            sb.append(message.substring(position, matcher.start()));
            sb.append(AQUA);
            System.out.println("event for " + matcher.group(1));
            sb.append(matcher.group().substring(1));
            sb.append(RESET);
            position = matcher.end();
        }
        sb.append(message.substring(position));
        System.out.println(sb);
        // Aaa <AQUA>hashtag-goes-here<RESET> bbb <AQUA>another-hashtag<RESET> ccc
    }

}
于 2013-10-19T17:35:10.267 回答
0

if不要在on中执行逻辑,sb而是在 else on 中执行str(或在sbafter appending中执行str,但您将在已处理的部分重复大量sb处理)。

不客气。

顺便提一句:

str.replace(str, str + ChatColor.RESET);

什么都不做,因为String实例是不可变的

于 2013-10-19T17:11:57.107 回答