Java用Regex實現${name}形式的字串模板執行個體_java

來源:互聯網
上載者:User

前言

相信大家可能曾遇到過這種情況,在開發中類似站內信的需求時,我們經常要使用字串模板,比如

尊敬的使用者${name}。。。。

裡面的${name}就可以替換為使用者的使用者名稱。

下面使用Regex簡單實現一下這個功能:

/**  * 根據索引值對填充字串,如("hello ${name}",{name:"xiaoming"})  * 輸出:  * @param content  * @param map  * @return  */ public static String renderString(String content, Map<String, String> map){  Set<Entry<String, String>> sets = map.entrySet();  for(Entry<String, String> entry : sets) {   String regex = "\\$\\{" + entry.getKey() + "\\}";   Pattern pattern = Pattern.compile(regex);   Matcher matcher = pattern.matcher(content);   content = matcher.replaceAll(entry.getValue());  }  return content; }

在map裡儲存了索引值對,然後擷取索引值對的集合,遍曆集合進行對字串的渲染

執行個體測試:

@Test public void renderString() {  String content = "hello ${name}, 1 2 3 4 5 ${six} 7, again ${name}. ";  Map<String, String> map = new HashMap<>();  map.put("name", "java");  map.put("six", "6");  content = StringHelper.renderString(content, map);  System.out.println(content); }

有兩個變數需要替換,name和six,對應的值分別為Java和6,同時name調用了兩次。

結果:

hello java, 1 2 3 4 5 6 7, again java. 

總結

以上就是關於Java利用Regex實現${name}形式的字串模板的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的協助,如果有疑問大家可以留言交流。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.