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", "Veera");
map.put("city", "Hyderabad");
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 Veera. I am from Hyderabad.
Become a Master in Big data at OnlineITGuru through big data hadoop training
No comments:
Post a Comment