替换字符串中的变量占位符

我的字符串看起来像这样:“你可以使用促销直到[开始日期+30]”。 我需要将[ Start Date + 30]占位符替换为实际日期 – 即销售的开始日期加上30天(或任何其他数字)。 [Start Date]也可能单独出现而没有添加数字。 此外,占位符内的任何额外空格都应该被忽略,并且不会使替换失败。

在Java中最好的方法是什么? 我正在考虑使用正则表达式来查找占位符但不确定如何进行解析部分。 如果它只是[开始日期]我会使用String.replaceAll()方法,但我不能使用它,因为我需要解析表达式并添加天数。

您应该使用StringBufferMatcher.appendReplacementMatcher.appendTail

这是一个完整的例子:

 String msg = "Hello [Start Date + 30] world [ Start Date ]."; StringBuffer sb = new StringBuffer(); Matcher m = Pattern.compile("\\[(.*?)\\]").matcher(msg); while (m.find()) { // What to replace String toReplace = m.group(1); // New value to insert int toInsert = 1000; // Parse toReplace (you probably want to do something better :) String[] parts = toReplace.split("\\+"); if (parts.length > 1) toInsert += Integer.parseInt(parts[1].trim()); // Append replaced match. m.appendReplacement(sb, "" + toInsert); } m.appendTail(sb); System.out.println(sb); 

输出:

 Hello 1030 world 1000.