簡體   English   中英

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

[英]Format a message using MessageFormat.format() in Java

我在資源包中存儲了一些消息。 我正在嘗試按如下方式格式化這些消息。

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一樣,盡管它沒有用。 需要進行哪些更改才能使其正常工作?

MessageFormat模式String添加一個額外的撇號'以確保顯示'字符

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

MessageFormat 模式中的撇號(又名單引號)以帶引號的字符串開頭,並且不會自行解釋。 來自javadoc

單引號本身必須由整個字符串中的雙引號 '' 表示。

String You\\\\'re相當於向String添加一個反斜杠字符,因此唯一的區別是You\\re將被生成而不是Youre (在雙引號解決方案''應用之前)

請確保您使用了雙撇號 ('')

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

編輯:

在字符串中,一對單引號可用於引用除單引號之外的任意字符。 例如,模式字符串“'{0}'”代表字符串“{0}”,而不是 FormatElement。 ...

任何不匹配的引號都被視為在給定模式結束時關閉。 例如,模式字符串“ ' {0}”被視為模式“ ' {0} ' ”。

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

您需要在“You'''re”中使用雙撇號而不是單撇號,例如:

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

使用撇號' (Unicode: \’ ) 而不是單引號'解決了問題,而不\’ \\'加倍。

對於 string.xml 中有 Android 問題的每個人,請使用 \\'\\' 而不是單引號。

這是一種不需要編輯代碼並且無論字符數如何都可以工作的方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM