基于正则的全文查找替换

下面的代码会把原文中的人名加粗(加<b>标签)



    public static void main(String[] args) {
        Pattern p = Pattern.compile("(name)([=:])([a-zA-Z]+)", Pattern.CASE_INSENSITIVE);
        Matcher m = p
                .matcher("Money was transferred to from one person [name=John] to another [Name:Kent]");
        StringBuffer newMsg = new StringBuffer();
        while (m.find()) {
            m.appendReplacement(newMsg, "$1$2<b>$3</b>");
        }
        m.appendTail(newMsg);
        System.out.println(newMsg.toString());
    }

执行结果:Money was transferred to from one person [name=<b>John</b>] to another [Name:<b>Kent</b>]

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.