[英]Custom format string : arguments in double brackets java
我正在处理android项目,但是我从服务器检索了一个包含所有本地化字符串的.xml
文件。 我遇到了一个问题,因为当字符串可以包含一个参数时,该参数将放在双括号中,例如:
您的帐户中有{{0}}美元
我不能使用常规的String.format()
函数。 我真的看不到如何解决此问题,应该创建一个自定义格式化程序吗?
编辑:字符串可以有多个参数
谢谢
使用String.replace()
而不是String.format()。
您还可以替换多个参数,例如,
String s = "{{0}} is friend with {{1}}";
s = s.replace("{{0}}","ABC");
s = s.replace("{{1}}","PQR");
一种更优雅的方法是使用正则表达式: {{((.*?)*?)}}
,这是我在c#
。
这也将允许您提取值。
Pattern pattern = Pattern.compile("{{((.*?)*?)}}");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
// Other stuff, like extracting values
String value = matcher.group(1)
// Then you can just String.replace the matches.
}
要创建具有更多参数的函数:
public String format(String input, String... args) {
// To access an element use e.g. args[0];
}
完整的工作功能可能是这样的(未测试):
public String format(String input, String... args) {
Pattern pattern = Pattern.compile("{{((.*?)*?)}}");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
String value = matcher.group(1);
// TODO: error handling
int index = Integer.parseInt(value);
if (index < args.length) {
input.replace(matcher.group(), args[index]);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.