Discuss / Java / 联系

联系

Topic source

o_0

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {
    private static Map<String, String> map = new HashMap<>();
    static {
        map.put("name", "Tom");
        map.put("lang", "Java");
    }
    
    public static void main(String[] args) throws Exception {
        String s = "Hello, ${name}! You are learning ${lang}!";
        String reg = "\\$\\{([a-zA-Z]+)\\}";
        Pattern pattern = Pattern.compile(reg);
        
        Matcher m = pattern.matcher(s);
        StringBuffer sb = new StringBuffer();
        while (m.find()) {
            //String key = s.substring(m.start() + 2, m.end() - 1);
            m.appendReplacement(sb, map.get(m.group(1)));
        }
        m.appendTail(sb);
        System.out.println(sb.toString()); // Hello, Tom! You are learning Java!
    }
}

  • 1

Reply