Java implements placeholder name replacement values

  • 2021-11-02 01:16:34
  • OfStack

Preface to the table of contents
Code
Principle

Preface

Placeholders should now be said to be more popular dynamic assignment, String. format (), through% s or other assignment; Or MessageFormat. format (), which is assigned by {0}, and the parameter name cannot be defined

There is a requirement in the project to replace the value of the corresponding parameter name according to a string of url with parameter name placeholders, thus having the following tool class.

Code


import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringFormatUtil {

    private static final Pattern pattern = Pattern.compile("\\{(.*?)\\}");
    private static Matcher matcher;

    private StringFormatUtil(){}


    /**
     *  Formatting string   Use in the string {key} Represents placeholders 
     *
     * @param sourStr
     *             String that needs to be matched 
     * @param param
     *             Parameter set 
     * @return
     */
    public static String format(String sourStr, Map<String, Object> param) {
        String tagerStr = sourStr;
        if (param == null)
            return tagerStr;
        try {
            matcher = pattern.matcher(tagerStr);
            while (matcher.find()) {
                String key = matcher.group();
                String keyclone = key.substring(1, key.length() - 1).trim();
                Object value = param.get(keyclone);
                if (value != null)
                    tagerStr = tagerStr.replace(key, value.toString());
            }
        }catch (Exception e){
            return null;
        }
        return tagerStr;
    }

    //public static void main(String[] args) {
    //    String url = "https://xxx.com/cfes?c={campaign_name}&af_siteid={af_siteid}&clickid={clickid}&android_id={android_id}&advertising_id={advertising_id}&idfa={idfa}";
    //    Map<String, Object> map = new LinkedHashMap<>();
    //    map.put("campaign_name", "111");
    //    map.put("af_siteid", "222");
    //    map.put("clickid", "333");
    //    map.put("android_id", "444");
    //    map.put("advertising_id", "555");
    //    map.put("idfa", "");
    //    System.out.println(format(url, map));
    //}
}

Results
https://xxx.com/cfes?c=111 & af_siteid=222 & clickid=333 & android_id=444 & advertising_id=555 & idfa=

Principle

From the above results, we can see that the placeholders corresponding to the parameter names have been replaced with corresponding values, and the principle is also very simple. According to the expression matching, find out each placeholder in str, and then find the placeholder name to do key according to the incoming map, and then get the corresponding value, and then replace it


Related articles: