자바 문자열 포맷,{}대체 자 는 이름 에 따라 인 스 턴 스 를 바 꿉 니 다.

긴 말 안 할 게 요.그냥 코드 보 세 요~

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
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;

  /**
   *              {key}     
   *
   * @param sourStr
   *              
   * @param param
   *         
   * @return
   */
  public static String stringFormat(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;
  }

  /**
   *              {key}                     (   get  )
   *
   * @param sourStr         
   *
   * @return
   */
  public static String stringFormat(String sourStr, Object obj) {
    String tagerStr = sourStr;
    matcher = pattern.matcher(tagerStr);
    if (obj == null)
      return tagerStr;

    PropertyDescriptor pd;
    Method getMethod;
    //   {}          
    while (matcher.find()) {
      String key = matcher.group();
      String keyclone = key.substring(1, key.length() - 1).trim();
      try {
        pd = new PropertyDescriptor(keyclone, obj.getClass());
        getMethod = pd.getReadMethod();//   get  
        Object value = getMethod.invoke(obj);
        if (value != null)
          tagerStr = tagerStr.replace(key, value.toString());
      } catch (Exception e) {
        // TODO Auto-generated catch block
        // Loggers.addException(e);
      }
    }
    return tagerStr;
  }

  /**
   *        (    )       {key}     
   *
   * @param sourStr
   *              
   * @param param
   *         
   * @return
   */
  public static String stringFormatAll(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;
  }

  /**
   *       ,       
   *   :sourStr = xxxxx{a}xxxx{b} ,param = {a:A,b:B}
   *   :targetStr = xxxxAxxxxB
   * @param sourStr
   * @param param
   * @return
   */
  public static String stringFormat(String sourStr, JSONObject 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) {
//    Map<String,Object> map = new HashMap<>();
//    map.put("id","111");
//    map.put("sss","ss");
//    JSONObject json = new JSONObject();
//    json.put("id","212");
//    json.put("fff","xxxx");
//    json.put("emmmmm",11);
//    stringFormat("sisas&{fff}_diwahwi%{id}{jio}",json);
  }
}
자바 의 자리 차지 문자 사용
두말 하지 않 고 먼저 코드 를 올리다.

package com.string.format;

public class StringFormat {
  //   %s,  sql,         ,           id
  public static void formSql(String tableName,String tableName2,String...strings){
    //sql    %s   
    String sql="delete from %s,%s where id in (%s)";
    //       
    String sqls="";
    //          
    for (String str : strings) {
      //           ,     
      sqls += str + ",";
    }
    //          ,  
    sqls=sqls.substring(0, sqls.length()-1);
    //format   sql        ,tableName,tableName2,         ,sqls          
    String s=String.format(sql, tableName,tableName2,sqls);
    //      sql
    System.out.println(s);
  }
  public static void main(String[] args) {
    //         ,    
    StringFormat.formSql("user","role", "1","3","5","7","9","33");
  }
}
사실 들 어 오 는 매개 변 수 는 배열 형식의 값 입 니 다.우 리 는 array[0],array[1]의 방식 으로 파 라 메 터 를 삽입 할 수 있 습 니 다.다만 매개 변수 개수 의 응용 이 원활 하지 않 을 뿐 배열 의 방식 으로 값 을 추출 하 는 것 이 좋 습 니 다.

public static void format(){
    String st="%s %s    %f,    %c,     %d%%,  %d,      %b";
    String s=String.format(st, "58  ","  ",3.5,' ',50,199,true);
    System.out.println(s);
  }
  public static void main(String[] args) {
    //         ,    
    //StringFormat.formSql("user","role", "1","3","5","7","9","33");
    format();
  }

public static void format(){
    //String st="%s %s    %f,    %c,     %d%%,  %d,      %b";
    //String s=String.format(st, "58  ","  ",3.5,' ',50,199,true);
    //System.out.println(s);
    SimpleDateFormat simple=new SimpleDateFormat("yyyy MM dd  HH mm ss ");
    String newDate=simple.format(new Date());
    String st1="%s %s    %s,    %s,     %s%%,  %s,      %s,     %s";
    String ss=String.format(st1, "58  ","  ","3.5",' ',"80","998","true",newDate);
    
    System.out.println(ss);
  }
  public static void main(String[] args) {
    //         ,    
    //StringFormat.formSql("user","role", "1","3","5","7","9","33");
    format();
  }

/*%S         
   * %c        
   * %b        
   * %d        
   * %%         
   * %n        
   * %t        
   * c         
   * F - -   
   * D / /   
   * rHH:MM:SS  12   
   *
   */
이 자바 문자열 은 포맷 되 었 습 니 다.{}자리 차지 문 자 는 이름 에 따라 인 스 턴 스 를 바 꾸 는 것 이 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.참고 하 시기 바 랍 니 다.많은 응원 바 랍 니 다.

좋은 웹페이지 즐겨찾기