This commit is contained in:
Looly 2021-08-17 16:14:28 +08:00
parent 83cbd4ea20
commit 0060d5ebbb
3 changed files with 61 additions and 44 deletions

View File

@ -3,6 +3,8 @@ package cn.hutool.core.text;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import java.util.Map;
/** /**
* 字符串格式化工具 * 字符串格式化工具
* *
@ -73,4 +75,34 @@ public class StrFormatter {
return sbuf.toString(); return sbuf.toString();
} }
/**
* 格式化文本使用 {varName} 占位<br>
* map = {a: "aValue", b: "bValue"} format("{a} and {b}", map) ---= aValue and bValue
*
* @param template 文本模板被替换的部分用 {key} 表示
* @param map 参数值对
* @param ignoreNull 是否忽略 {@code null} 忽略则 {@code null} 值对应的变量不被替换否则替换为""
* @return 格式化后的文本
* @since 5.7.10
*/
public static String format(CharSequence template, Map<?, ?> map, boolean ignoreNull) {
if (null == template) {
return null;
}
if (null == map || map.isEmpty()) {
return template.toString();
}
String template2 = template.toString();
String value;
for (Map.Entry<?, ?> entry : map.entrySet()) {
value = StrUtil.utf8Str(entry.getValue());
if (null == value && ignoreNull) {
continue;
}
template2 = StrUtil.replace(template2, "{" + entry.getKey() + "}", value);
}
return template2;
}
} }

View File

@ -2,6 +2,7 @@ package cn.hutool.core.util;
import cn.hutool.core.text.CharSequenceUtil; import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.text.StrBuilder; import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.text.StrPool; import cn.hutool.core.text.StrPool;
import cn.hutool.core.text.TextSimilarity; import cn.hutool.core.text.TextSimilarity;
@ -454,22 +455,6 @@ public class StrUtil extends CharSequenceUtil implements StrPool {
* @since 5.4.3 * @since 5.4.3
*/ */
public static String format(CharSequence template, Map<?, ?> map, boolean ignoreNull) { public static String format(CharSequence template, Map<?, ?> map, boolean ignoreNull) {
if (null == template) { return StrFormatter.format(template, map, ignoreNull);
return null;
}
if (null == map || map.isEmpty()) {
return template.toString();
}
String template2 = template.toString();
String value;
for (Map.Entry<?, ?> entry : map.entrySet()) {
value = utf8Str(entry.getValue());
if (null == value && ignoreNull) {
continue;
}
template2 = replace(template2, "{" + entry.getKey() + "}", value);
}
return template2;
} }
} }

View File

@ -33,7 +33,7 @@ public class QrConfig {
protected Integer backColor = WHITE; protected Integer backColor = WHITE;
/** 边距1~4 */ /** 边距1~4 */
protected Integer margin = 2; protected Integer margin = 2;
/** 设置二维码中的信息量,可设置1-40的整数 */ /** 设置二维码中的信息量,可设置0-40的整数 */
protected Integer qrVersion; protected Integer qrVersion;
/** 纠错级别 */ /** 纠错级别 */
protected ErrorCorrectionLevel errorCorrection = ErrorCorrectionLevel.M; protected ErrorCorrectionLevel errorCorrection = ErrorCorrectionLevel.M;