java regular expression find and replace

后端 未结 7 2136
执念已碎
执念已碎 2020-12-14 21:37

I am trying to find environment variables in input and replace them with values.

The pattern of env variable is ${\\\\.}

Pattern myPatte         


        
相关标签:
7条回答
  • 2020-12-14 22:10
        Map<String, String> replacements = new HashMap<String, String>() {
            {
                put("env1", "1");
                put("env2", "2");
                put("env3", "3");
    
            }
        };
    
        String line = "${env1}sojods${env2}${env3}";
    
        String rx = "\\$\\{(.*?)\\}";
    
        StringBuffer sb = new StringBuffer();
        Pattern p = Pattern.compile(rx);
        Matcher m = p.matcher(line);
    
        while (m.find()) {
            // Avoids throwing a NullPointerException in the case that you
            // Don't have a replacement defined in the map for the match
            String repString = replacements.get(m.group(1));
            if (repString != null)
                m.appendReplacement(sb, repString);
        }
        m.appendTail(sb);
    
        System.out.println(sb.toString());
    

    In the above example we can use map with just key and values --keys can be env1 ,env2 ..

    0 讨论(0)
提交回复
热议问题