在这种情况下,我经常使用 MessageFormat
作为索引参数:
String text = MessageFormat.format("The goal is {0} points.", 5);
现在我遇到了一种情况,我需要处理以下格式的消息:
"The {title} is {number} points."
因此,值不再被索引,占位符是字符串。我该如何处理这种情况并具有与 MessageFormat
相同的功能?如果参数未索引,MessageFormat
会抛出解析异常。
谢谢。
最佳答案
一个简单的建议包括用正则表达式匹配替换作为索引的文本参数,然后像平常一样使用它。这是一个例子:
int paramIndex = 0;
String text = "The {title} is {number} points.";
String paramRegex = "\\{(.*?)\\}";
Pattern paramPattern = Pattern.compile(paramRegex);
Matcher matcher = paramPattern.matcher(text);
while(matcher.find())
text = text.replace(matcher.group(), "{" + paramIndex++ + "}");
text = MessageFormat.format(text, "kick", "3");
在这种情况下,text
将等于最后的“踢球为 3 分”。
关于java - 命名消息参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28160492/