Java 消息格式化程序不工作

Java Message Formatter is not working

我有字符串模板

xxxxxxxx xxxxx-xx: [{0}] xxxxxxx xxxxx xxxxxx xxxxxx [{1}] xxxxxx xxxx xxxxx'x xxxxx xxxxxx xxxx [{2}]

即使我提供了所有三个参数仍然无效

public static void main(String[] args) {
    String s = "xxxxxxxx xxxxx-xx: [{0}] xxxxxxx xxxxx xxxxxx xxxxxx [{1}] xxxxxx xxxx xxxxx'x xxxxx xxxxxx xxxx [{2}]";

    System.out.println(MessageFormat.format(s,"1","2","3"));
}

输出为:

xxxxxxxx xxxxx-xx: [1] xxxxxxx xxxxx xxxxxx xxxxxx [2] xxxxxx xxxx xxxxxx xxxxx xxxxxx xxxx [{2}]

查看输出,它输出 {2} 而不是 3,我找不到它为什么不工作的原因。是错误还是我遗漏了什么?

这是因为您的字符串中有 '。你需要逃避它或者你错过了一个。

您的问题出在单引号中 ' 您必须使用双引号 '' 而不是单引号 :

xxxxx''x

阅读有关单引号的文档(MessageFormat)

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String. For example, pattern string "'{''}'" is interpreted as a sequence of '{ (start of quoting and a left curly brace), '' (a single quote), and }' (a right curly brace and end of quoting), not '{' and '}' (quoted left and right curly braces): representing string "{'}", not "{}".

确实是撇号,您需要用另一个撇号转义它,例如:''xxx。它在文档中顺便说一句:

Within a String, '' (two single quotes ) represents a single quote.