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

发布于 2021-01-30 15:47:36

我的字符串看起来像这样:“您可以在[开始日期+ 30]之前使用促销。” 我需要将[ Start Date + 30]占位符替换为实际日期-
这是销售的开始日期加上30天(或其他任何数字)。[Start Date]也可以单独显示而无需添加数字。同样,占位符内的所有多余空格都应被忽略,并且不要使替换失败。

用Java做到这一点的最佳方法是什么?我正在考虑用于查找占位符的正则表达式,但不确定如何执行解析部分。如果只是[开始日期],我将使用该String.replaceAll()方法,但由于需要解析表达式并添加天数,因此无法使用。

关注者
0
被浏览
87
1 个回答
  • 面试哥
    面试哥 2021-01-30
    为面试而生,有面试问题,就找面试哥。

    您应该使用StringBufferand
    Matcher.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.
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看