无法用 java 替换 html 字符串中的特定文本

Can not replace a certain text in an html string with java

我有一个方法可以在将 html 字符串发送到客户电子邮件之前替换它的一部分。 我尝试使用 java replaceAll() 方法 但没有成功。 这是我到目前为止尝试过的:

data.replaceAll("dd%title%dd", "This is the Title");
data.replaceAll("dd%message%dd", "This is the message body");

但是当我尝试这个时它不起作用并且我一直在获取字符串而没有被替换。 这是我在雅虎邮箱收件箱中收到的邮件图片: Yahoo mail screenshot

我试过使用正则表达式来替换,但它没有像我预期的那样工作。

这是我现在拥有的

/******************* CONSTRUCTING THE MESSAGE TRANSLATOR ********************/
    private String msgTranslate(String subject, String messaging){
        // HERE WE START CONSTRUCTING THE MESSAGE TRANSLATE
        String content="";
        String data="";
        DjadeUtil util=new DjadeUtil();
        // NOW LETS START PROCESSING
        if(messaging!=null && subject!=null){
            // Now lets read
            try {
                data=util.readByScanner(TEMPLATESOURCE);
                // Now lets check
                if(data.length()>0){
                    // Here we start matching to replace
                    StringBuffer sb = new StringBuffer(data.length());
                    Pattern patA = Pattern.compile("dd%title%dd");
                    Pattern patB = Pattern.compile("dd%message%dd");

                    Matcher mA = patA.matcher(data);
                    Matcher mB = patB.matcher(data);

                    while (mA.find()) {
                        mA.appendReplacement(sb, subject);
                    }// End of while loop

                    while (mB.find()) {
                        mB.appendReplacement(sb, messaging);
                    }// End of while loop

                    //HERE WE STORE NEW CHANGE
                    mA.appendTail(sb);
                    mB.appendTail(sb);
                    content=sb.toString();
                }
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        // Here we return string
        return content;
    }

这是我现在的 html 字符串

<div style="line-height: 20px;">
                    <!-- THE BODY OF NEWSLATER GOES HERE //-->
                    <div class="newTitle">dd%title%dd</div>
                    <div class="newBody">dd%message%dd</div>
                    <div class="newButtons">
                        <button class="butNews" onclick="window.location='https://napoleoninvestment.net/?page_id=12'">Join our Telegram</button>
                        <button class="butNews" onclick="window.location='https://napoleoninvestment.net/?page_id=391'">Invest Now</button>
                    </div>
                </div>

我想用 "This is the Title" 替换 "dd%title%dd",用 "This is the message body" 替换 "dd%message%dd"。 我不知道哪里出了问题。任何帮助将不胜感激

我想你忘记重新分配 data。您不需要 replaceAll 因为不需要正则表达式匹配。

data = data.replace("dd%title%dd", "This is the Title");
data = data.replace("dd%message%dd", "This is the message body");