【问题标题】:Custom format string : arguments in double brackets java自定义格式字符串:双括号中的参数 java
【发布时间】:2018-08-08 08:04:21
【问题描述】:

我正在处理 android 项目,但我从服务器检索了一个包含所有本地化字符串的 .xml 文件。我遇到了一个问题,因为当字符串可以包含参数时,该参数设置在双括号中,例如:

您的帐户中有 {{0}} 美元

我不能使用常规的String.format() 函数。我真的不明白我该如何解决这个问题,我应该创建一个自定义格式化程序吗?

编辑:字符串可以有多个参数

谢谢

【问题讨论】:

  • 呃,解决什么问题?
  • 我怎样才能执行String.format("You have {{0}} dollar(s) on your account", 120) 之类的操作,这将返回您的帐户中有 120 美元

标签: java android formatting


【解决方案1】:

使用String.replace() 代替 String.format()。

你也可以替换多个参数 Like,

String s = "{{0}} is friend with {{1}}"; 
s = s.replace("{{0}}","ABC"); 
s = s.replace("{{1}}","PQR");

【讨论】:

  • 好的,谢谢,有没有办法制作一个可以接受多个参数的自定义格式化程序?
  • 所有参数名都不一样?
  • 是的,例如“{{0}} 是 {{1}} 的朋友”
  • 有没有办法创建像myFormatter("{{0}} is friend with {{1}}","William", "Antoine")这样的函数,这个函数也可以使用一个或多个参数
  • @AntoineD 我为你写了一些示例函数。
【解决方案2】:

更优雅的方法是使用正则表达式:{{((.*?)*?)}},我在 c# 中使用过。

https://regexr.com/3tkl9

这也将允许您提取值。

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]);
        }
    }
}

【讨论】:

  • @Giovanni int index = Integer.parseInt(value); 可能会抛出异常?
  • 是的,您需要检查该值是什么,以及是否为数字。
  • 如果匹配类似于{{iAmNotADigit}},它将崩溃
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 2013-08-20
相关资源
最近更新 更多