How to use Apache strsubstitutor

Source: Internet
Author: User

In Java, it's hard to use a formatted string, whether it's String.Format or Messageformat. Velocity is good, but it's too heavy. Today, we recommend Apache Commons-lang in Strsubstitutor.

Document Address: https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/StrSubstitutor.html

Strsubstitutor in Apache Commons-lang3 package, to use, please add the following dependencies in the Pom.xml:

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

1, directly replace the system property values

strsubstitutor.replacesystemproperties (    "You is running with java.version = ${java.version} and Os.name = ${os.name}. ");

2. Replace placeholders in strings with map

Map Valuesmap = HashMap ();
Valuesmap.put ("Animal", "Quick brown fox");
Valuesmap.put ("target", "lazy dog"= "The ${animal} jumped over the ${target}." ;
New= Sub.replace (templatestring);

Resolvedstring Result: The quick brown fox jumped over the lazy dog.

3. Strsubstitutor will replace variables recursively, such as:

map<string, object> params = maps.newhashmap (); params.put ("name", "${x}");p arams.put ("x", "Y");
New Strsubstitutor (params);

String Hello2 = "${name}";
System.out.println (Strsubstitutor.replace (Hello2));

The final output is: Y

4, sometimes the variable is also nested other variables, this strsubstitutor is also supported, but to call the next setenablesubstitutioninvariables can be.

map<string, object> params = maps.newhashmap ();p arams.put ("jre-1.8", "java-version-1.8"); Params.put ("java.specification.version", "1.8"new  strsubstitutor (params);           Strsubstitutor.setenablesubstitutioninvariables (true); System.out.println (Strsubstitutor.replace ("${jre-${java.specification.version}}");

Output: java-version-1.8

How to use Apache strsubstitutor

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.