替换字符串中的变量占位符
我的字符串看起来像这样:“您可以在[开始日期+ 30]之前使用促销。” 我需要将[ Start Date + 30]
占位符替换为实际日期-
这是销售的开始日期加上30天(或其他任何数字)。[Start
Date]
也可以单独显示而无需添加数字。同样,占位符内的所有多余空格都应被忽略,并且不要使替换失败。
用Java做到这一点的最佳方法是什么?我正在考虑用于查找占位符的正则表达式,但不确定如何执行解析部分。如果只是[开始日期],我将使用该String.replaceAll()
方法,但由于需要解析表达式并添加天数,因此无法使用。
-
您应该使用
StringBuffer
and
Matcher.appendReplacement
和Matcher.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.