用正则来替换字符串

下面的例子演示matcher的appendReplacement和appendTail用法,替换字符串对应的值,并返回新的字符串。该用法可以用于简单的html字符串的替换,当如果html结果更复杂,应该使用HTML解析库,Jsoup等 public class ReplaceTpl { pu

下面的例子演示matcher的appendReplacement和appendTail用法,替换字符串对应的值,并返回新的字符串。该用法可以用于简单的html字符串的替换,当如果html结果更复杂,应该使用HTML解析库,Jsoup等

public class ReplaceTpl {
    public static void main(String[] args) {
        String input = ".....<p>key:a,value:xx</p>....<p>key:b,value:xx</p>...";
        Map<String, String> codeToTextMap = new HashMap<>();
        codeToTextMap.put("a", "AAA");
        codeToTextMap.put("b", "BBB");

        // 定义正则表达式
        Pattern pattern = Pattern.compile("<p>key:(.+?),value:(.*?)</p>");
        // 创建 matcher 对象;
        Matcher matcher = pattern.matcher(input);

        // 使用 StringBuffer 来构建替换后的字符串
        StringBuffer result = new StringBuffer();

        // 使用 matcher 的 replaceAll 方法进行替换
        while (matcher.find()) {
            String code = matcher.group(1); // 获取 code
            String replacement = codeToTextMap.get(code); // 从 map 中获取对应的替换文本

            // 构建新的匹配项
            String replacementItem = "<p>key:" + code + ",value:" + replacement + "</p>";

            // 替换原始字符串中的匹配项
            matcher.appendReplacement(result, replacementItem);
        }

        // 添加剩余的部分
        matcher.appendTail(result);
        // 输出结果
        System.out.println(result.toString());
    }
}

LICENSED UNDER CC BY-NC-SA 4.0
Comment