覺得很難給文章命名...若有人有好的想法..可以和我分享,非常感謝..

 

以下開始:

取代文字有很多種方式

 

先說明使用到這些程式的狀況,我們是做網頁的系統

會提供USER設定Email模板,然後在模板內會設定參數,像是${data}、${count}

這些參數可能會依照不同功能,帶入不同的資訊,所以就會需要取代內容的程式

 

原本的做法是使用"replaceAll",但可能因為資料內容有問題發生了錯誤

18:22:21,232 WARN  [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0) ARJUNA012095: Abort of action id 0:ffffc0a89397:-3ac9f5c4:6094b02d:452 invoked while multiple threads active within it.
18:22:21,250 WARN  [com.arjuna.ats.arjuna] (Transaction Reaper Worker 0) ARJUNA012381: Action id 0:ffffc0a89397:-3ac9f5c4:6094b02d:452 completed with multiple threads - thread default task-21 was in progress with org.jboss.as.ee.component.ManagedReferenceMethodInterceptor.processInvocation(ManagedReferenceMethodInterceptor.java:58)

 

我的資料內容是html格式的內容,不確定是哪一段被判斷為regex,而造成錯誤

所以為了避開這個錯誤,就改成使用"replace"

 

因為replaceAll會取代所有的,但是replace只會取代第一個

所以需要再判斷是否仍有未取代到的參數

這邊記錄調整的兩種方式

 

方法一

使用Patterm 和Matcher

image

 

文字程式如下

public String replaceContent(String content, Map<String, Object> replaceParams) throws Exception {
        
        String content_s = new String(content);
        for(String key:replaceParams.keySet()){
            String patternRegex = "\\$\\{" + StringUtil.nvl(key) + "\\}";
            String patternString = "${" + StringUtil.nvl(key) + "}";
            
            Pattern pattern = Pattern.compile(patternRegex);
            Matcher matcher = pattern.matcher(content_s);

            while (matcher.find()) {
                content_s = content_s.replace(patternString, replaceParams.get(key).toString());

            }
        }
        
        content_s = content_s.replaceAll("\\$\\{[\\w!@#$%^&*()]*\\}+", "");
        return content_s;
    }

 

方法二

使用StringUtils.count()

這個方式相較於方法一 ,感覺比較容易看懂在做甚麼

image

文字程式如下

public String replaceContent(String content, Map<String, Object> replaceParams) throws Exception {
        
        String content_s = new String(content);
        for(String key:replaceParams.keySet()){
            String patternString = "${" + StringUtil.nvl(key) + "}";

            for (int i = 0; i <StringUtil.count(content_s, patternString); i++){
                content_s = content_s.replace(patternString, replaceParams.get(key).toString());
            }
            
        }
        
        content_s = content_s.replaceAll("\\$\\{[\\w!@#$%^&*()]*\\}+", "");
        return content_s;
    }

 

另外補充:

若是要將空格取代成空字串

第一個會讓人想到的寫法就是

image

String replace = " ABCD";
replace.replace(" ", "");

 

但有一些特殊狀況會讓空白無法被取代掉,像是看起來是空白,但其實是"\r\n",甚至是"不間段空格"

關於不間段空格詳細說明是參考 https://blog.csdn.net/lvxiangan/article/details/88974955

會導致空白無法被正常被取代

所以程式會調整為

image

String replace = " ABCD";
replace.replaceAll("\\s*", "").replaceAll("\\u00A0+", "");

 

 

 

 

arrow
arrow

    我的暱稱 發表在 痞客邦 留言(0) 人氣()