在 Java 中使用 MessageFormat.Format()格式化消息

我已经在一个资源包中存储了一些消息。

import java.text.MessageFormat;


String text = MessageFormat.format("You're about to delete {0} rows.", 5);
System.out.println(text);

假设第一个参数,即实际的消息存储在一个属性文件中,并以某种方式检索该属性文件。

第二个参数(即5)是一个动态值,应该放置在占位符 {0}中,这是不会发生的。下一行是,

即将删除{0}行。

占位符不会被实际参数替换。


这里是撇号 -You're。我试图像平常一样逃避 You\\'re,虽然它没有工作。需要做出哪些改变才能使其发挥作用?

142893 次浏览

Add an extra apostrophe ' to the MessageFormat pattern String to ensure the ' character is displayed

String text =
java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
^

An apostrophe (aka single quote) in a MessageFormat pattern starts a quoted string and is not interpreted on its own. From the javadoc

A single quote itself must be represented by doubled single quotes '' throughout a String.

The String You\\'re is equivalent to adding a backslash character to the String so the only difference will be that You\re will be produced rather than Youre. (before double quote solution '' applied)

You need to use double apostrophe instead of single in the "You''re", eg:

String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);

Just be sure you have used double apostrophe ('')

String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);

Edit:

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. ...

Any unmatched quote is treated as closed at the end of the given pattern. For example, pattern string "'{0}" is treated as pattern "'{0}'".

Source http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html

For everyone that has Android problems in the string.xml, use \'\' instead of single quote.

Using an apostrophe (Unicode: \u2019) instead of a single quote ' fixed the issue without doubling the \'.

Here is a method that does not require editing the code and works regardless of the number of characters.

String text =
java.text.MessageFormat.format(
"You're about to delete {0} rows.".replaceAll("'", "''"), 5);