用动态值替换字符串中动态的标签数量 - Java

时间:2013-10-22 09:49:47

标签: java string

我搜索了这个网站,也搜索了谷歌,但我找不到我面临的这个问题的具体解决方案。

语言:Java

我有一个字符串,让我们说:

String message = "I would like to have <variable>KG of rice and <variable>Litre of Milk. I only have $<variable>, is this sufficient?"

现在,用户将有三个文本字段,这些字段将被排序以填充变量。

约束:

1)用户可以在消息中输入任意数量的标签

2)将出现的文本字段数基于消息中的标记数

无论如何,我可以将原始消息替换为:

“我想要{0} KG米饭和{1}升牛奶。我只有$ {2},这还够吗?”

我正在更改为{X},其中X =订单号。怎么做到这一点?

我曾经想过使用格式化程序,匹配器但是我一直都处于死胡同状态。那么,有人可以帮我吗?

谢谢

5 个答案:

答案 0 :(得分:4)

我不完全确定您想要达到的目标,但如果我理解正确的问题并且您希望用<variable>替换用户输入中的字符串{0}{1}{2}先后我认为这就是答案:

您可以使用Matcher匹配所有<variable>,然后迭代匹配并使用appendReplacement将其替换为{0},{{1} },{1}

所以

{2}

答案 1 :(得分:3)

试试这个。

String s = java.text.MessageFormat.format("I would like to have {0} KG of rice and {1} Litre of Milk. I only have ${2}, is this sufficient?",new String[]{"100","5","50"});
System.out.println(s);

<强>输出

我想要100公斤大米和5公升牛奶。我只有50美元,这还够吗?

答案 2 :(得分:0)

String mesage = "I would like to have " + kg + 
"KG of rice and " + litre + "Litre of Milk. I only have $" + dollor + " 
is this sufficient?";

答案 3 :(得分:0)

您可以使用以下内容:

int i = 0;
while(message.contains("<variable>")) {
    message = message.replaceFirst("<variable>", "{" + i + "}");
    i++;
}

这将导致:

I would like to have {0}KG of rice and {1}Litre of Milk. I only have ${2}, is this sufficient?

答案 4 :(得分:0)

String.format 代替循环很方便。看看下面:

component

参考 https://www.javatpoint.com/java-string-format 了解不同的格式说明符:%d %s 等

相关问题