tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Tools and Libs > Commons Lang3 > General > Replace with Custom Prefix and Suffix

Replace with Custom Prefix and Suffix 

Apache Commons Lang 3.0 is a java library with lot of utilities and reusable components. This requires the library commons-lang3-3.0.1.jar to be in classpath. The following example shows using StrSubstitutor.replace() API. It replaces all the occurrences of variables in the given source object with their matching values from the map. This method allows us to specify a custom variable prefix and suffix.

File Name  :  
com/bethecoder/tutorials/commons_lang/tests/gen/StringReplaceTest2.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.commons_lang.tests.gen;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.text.StrSubstitutor;

public class StringReplaceTest2 {

  /**
   @param args
   */
  public static void main(String[] args) {
      
    Map<String, Object> valueMap = new HashMap<String, Object>();
    valueMap.put("state""Andhra Pradesh");
    valueMap.put("capital""Hyderabad");
    
    String varPrefix = "#{";
    String varSuffix = "}";
    String template = "The capital of #{state} is #{capital}";
    System.out.println(StrSubstitutor.replace(template, valueMap, varPrefix, varSuffix));
    
    varPrefix = "<<";
    varSuffix = ">>";
    template = "The capital of <<state>> is <<capital>>";
    System.out.println(StrSubstitutor.replace(template, valueMap, varPrefix, varSuffix));
  }

}
   

It gives the following output,
The capital of Andhra Pradesh is Hyderabad
The capital of Andhra Pradesh is Hyderabad



 
  


  
bl  br