자바 문자열 포맷,{}대체 자 는 이름 에 따라 인 스 턴 스 를 바 꿉 니 다.
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
*
*/
이 자바 문자열 은 포맷 되 었 습 니 다.{}자리 차지 문 자 는 이름 에 따라 인 스 턴 스 를 바 꾸 는 것 이 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.참고 하 시기 바 랍 니 다.많은 응원 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.