【问题标题】:Getting certain part of string with delimiters使用分隔符获取字符串的某些部分
【发布时间】:2021-01-24 12:30:15
【问题描述】:

我正在使用 String message = event.message.getFormattedText(); 获取消息的文本,目前我将 Minecraft 玩家的用户名更改为 message = message.replaceAll("(?i)" + Minecraft.getMinecraft().thePlayer.getName(), NameAndColorUtils.nickname);。但是,有些消息的结构如下:

Title [RANK] Username: Message 


Rookie [VIP] Player: Hello!

我希望能够同时获取分隔符“[”和“]”,以及它们之间的文本,并将其替换为我选择的字符串。例如,将 [VIP] 更改为 [MVP],或完全删除排名(取决于用户的输入)。我该怎么做呢?

【问题讨论】:

    标签: java string message minecraft delimiter


    【解决方案1】:

    使用正则表达式替换循环,例如像这样:

    static String replace(String message) {
        StringBuffer buf = new StringBuffer();
        Matcher m = Pattern.compile("\\[([^\\]]+)\\](\\s*)").matcher(message);
        while (m.find()) {
            String tag = m.group(1);
            if (tag.equals("RANK")) {
                // Remove tag and trailing space
                m.appendReplacement(buf, "");
            } else if (tag.equals("VIP")) {
                // Replace tag and keep trailing space
                m.appendReplacement(buf, "{MVP}" + m.group(2));
            }
            // No else clause means that text is left intact for unknown tags
        }
        return m.appendTail(buf).toString();
    }
    

    测试

    System.out.println(replace("Title [RANK] Username: Message"));
    System.out.println(replace("Rookie [VIP] Player: Hello!"));
    System.out.println(replace("Hello [FOO] World"));
    

    输出

    Title Username: Message
    Rookie {MVP} Player: Hello!
    Hello [FOO] World
    

    【讨论】:

    • 有什么方法可以直接从用户的消息中获取标签,然后在那里替换它?例如,如果用户发送消息 [MVP] Player: Hello!它只能从用户的消息中获取标签,然后用 [VIP] 替换标签?
    • @Gungee 这不是这段代码在做什么吗?从消息中获取标签,然后决定如何处理它,例如用别的东西代替它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多