java regular expression find and replace

后端 未结 7 2122
执念已碎
执念已碎 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 21:58

    You can use a StringBuffer in combination with the Matcher appendReplacement() method, but if the the pattern does not match, there is no point in creating the StringBuffer.

    For example, here is a pattern that matches ${...}. Group 1 is the contents between the braces.

    static Pattern rxTemplate = Pattern.compile("\\$\\{([^}\\s]+)\\}");
    

    And here is sample function that uses that pattern.

    private static String replaceTemplateString(String text) {
        StringBuffer sb = null;
        Matcher m = rxTemplate.matcher(text);
        while (m.find()) {
            String t = m.group(1);
            t = t.toUpperCase(); // LOOKUP YOUR REPLACEMENT HERE
    
            if (sb == null) {
                sb = new StringBuffer(text.length());
            }
            m.appendReplacement(sb, t);
        }
        if (sb == null) {
            return text;
        } else {
            m.appendTail(sb);
            return sb.toString();
        }
    }
    

提交回复
热议问题