加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用正则表达式进行多个变量的替换

发布时间:2020-12-14 06:45:50 所属栏目:百科 来源:网络整理
导读:使用正则表达式进行多个变量的替换 假设需要根据一个变量表去替换文本中的内容,要如何替换呢?这里不能直接使用replaceFirst或者replaceAll的,应该使用appendReplacement。看示例如下: Map String , String variables = new HashMap String , String ();

使用正则表达式进行多个变量的替换

假设需要根据一个变量表去替换文本中的内容,要如何替换呢?这里不能直接使用replaceFirst或者replaceAll的,应该使用appendReplacement。看示例如下:

Map<String,String> variables = new HashMap<String,String>();
    variables.put("name","ben");
    variables.put("age","23");

    String data = "Hello,i'm $name. I am $age years old.";
    String funcPattern = "$(w+)b";
    Pattern p = Pattern.compile(funcPattern);

    StringBuffer sb = new StringBuffer();
    Matcher m = p.matcher(data);

    while(m.find()){
        String key = m.group(1);
        if(variables.containsKey(key)){
            String value = variables.get(key);
            m.appendReplacement(sb,value);
        }
    }
     m.appendTail(sb);
     System.out.println(sb.toString());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读