Thursday, July 19, 2012

Apache Commons

Apache commons has an excellent Utility class, that is : StrSubstitutor.

Example 1:

String testString = "This is a test string @1@ @2@ @3@ that needs to be replaced with value";

Map<String,String> properties = new HashMap<String,String>();
        properties.put("1", "one");
        properties.put("2", "two");
        properties.put("3", "three");

StrSubstitutor substitutor = new StrSubstitutor(properties,"@","@");

System.out.println(substitutor.replace(testString));

Output:
This is a test string one two three that needs to be replaced with value

Example 2:

The default behavior of this class works similar to "Velocity Templates". i.e., ${var_name}.

  Map<String, String> map = new HashMap<String,String>();
        map.put("name", "pramod");
        map.put("city", "karimnagar");
       
 String text = "My name is ${name}. I am from ${city}.";
       
 StrSubstitutor substitutor = new StrSubstitutor(map);
       
 System.out.println(substitutor.replace(text));

Output:
My name is pramod. I am from karimnagar.