Apache StrSubstitutor使用方法

來源:互聯網
上載者:User

標籤:targe   oci   cat   anim   param   hello   print   tor   spec   

Java中,對于格式化字串,不論是String.format,還是MessageFormat,都很難用。Velocity倒是不錯,可就是太重。今天給大家推薦Apache commons-lang中的StrSubstitutor。

文檔地址:https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/StrSubstitutor.html

StrSubstitutor在apache的commons-lang3包中,要使用,請在pom.xml裡加入如下依賴:

1 <dependency>2     <groupId>org.apache.commons</groupId>3     <artifactId>commons-lang3</artifactId>4     <version>3.4</version>5 </dependency>

1、直接替換系統屬性值

StrSubstitutor.replaceSystemProperties(    "You are running with java.version = ${java.version} and os.name = ${os.name}.");

2、使用Map替換字串中的預留位置

Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);String resolvedString = sub.replace(templateString);

resolvedString的結果:The quick brown fox jumped over the lazy dog.

3、StrSubstitutor會遞迴地替換變數,比如:

Map<String, Object> params = Maps.newHashMap();params.put("name", "${x}");params.put("x", "y");
StrSubstitutor strSubstitutor = new StrSubstitutor(params);

String hello2 = "${name}";
System.out.println(strSubstitutor.replace(hello2));

最後會輸出:y

4、有時變數內還嵌套其它變數,這個StrSubstitutor也是支援的,不過要調用下setEnableSubstitutionInVariables才可以。

Map<String, Object> params = Maps.newHashMap();params.put("jre-1.8", "java-version-1.8");params.put("java.specification.version", "1.8");StrSubstitutor strSubstitutor = new StrSubstitutor(params);           strSubstitutor.setEnableSubstitutionInVariables(true);System.out.println(strSubstitutor.replace("${jre-${java.specification.version}}"));

輸出:java-version-1.8

Apache StrSubstitutor使用方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.