替换字符串中的变量占位符
我的字符串看起来像这样:“您可以在[开始日期+ 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.
-
oracle SQL 中的格式化字符串,用字符串末尾给出的变量名替换占位符
2021-06-04 关注 0 浏览95 1答案
-
无法解析字符串值中的占位符
2021-01-30 关注 0 浏览96 1答案
-
无法解析字符串值中的占位符
2021-02-02 关注 0 浏览139 1答案
-
Spring Boot无法解析字符串中的占位符
2021-02-02 关注 0 浏览88 1答案
-
Java用占位符生成字符串
2021-01-30 关注 0 浏览97 1答案
-
以字符串格式命名的占位符
2021-01-31 关注 0 浏览112 1答案
-
替换字符串C#中的换行符
2021-02-02 关注 0 浏览58 1答案
-
替换字符串 C# 中的换行符
2022-03-22 关注 0 浏览29 1答案
-
为什么PHP不替换字符串中的变量?
2021-02-02 关注 0 浏览60 1答案
-
如何用 元素替换字符串中的所有换行符?
2022-03-22 关注 0 浏览34 1答案