
您应该使用
StringBufferand
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.
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)