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

替换字符串中的变量占位符,第1张

替换字符串中的变量占位

您应该使用

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.


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5506649.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-13
下一篇2022-12-13

发表评论

登录后才能评论

评论列表(0条)

    保存