mirror of https://gitee.com/makejava/EasyCode.git
新增:$tool工具中增加toUnicode(String[, Boolean])方法,用于将字符串转换为UNICODE编码。
This commit is contained in:
parent
1aae2a0e29
commit
d593f13710
|
@ -277,6 +277,54 @@ public class GlobalTool extends NameUtils {
|
|||
}
|
||||
}
|
||||
|
||||
// 中文及中文符号正则表达式
|
||||
public static final String CHINESE_REGEX = "[\u4e00-\u9fa5–—‘’“”…、。〈〉《》「」『』【】〔〕!(),.:;?]";
|
||||
|
||||
/**
|
||||
* 字符串转unicode编码(默认只转换CHINESE_REGEX匹配到的字符)
|
||||
* @param str 字符串
|
||||
* @return 转码后的字符串
|
||||
*/
|
||||
public String toUnicode(String str) {
|
||||
return toUnicode(str, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 字符串转unicode编码
|
||||
* @param str 字符串
|
||||
* @param transAll true转换所有字符,false只转换CHINESE_REGEX匹配到的字符
|
||||
* @return 转码后的字符串
|
||||
*/
|
||||
public String toUnicode(String str, Boolean transAll) {
|
||||
if (null == str) {
|
||||
return null;
|
||||
}
|
||||
if (str.length() <= 0) {
|
||||
return null;
|
||||
}
|
||||
if (null == transAll) {
|
||||
transAll = false;
|
||||
}
|
||||
|
||||
StringBuffer sb = new StringBuffer();
|
||||
if (transAll) {
|
||||
for (char c : str.toCharArray()) {
|
||||
sb.append(String.format("\\u%04x", (int) c));
|
||||
}
|
||||
} else {
|
||||
for (char c : str.toCharArray()) {
|
||||
// 中文范围
|
||||
if (String.valueOf(c).matches(CHINESE_REGEX)) {
|
||||
sb.append(String.format("\\u%04x", (int) c));
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 远程调用服务
|
||||
*
|
||||
|
|
|
@ -57,6 +57,7 @@
|
|||
service(String serviceName, Object... param)远程服务调用
|
||||
parseJson(String) 将字符串转Map对象
|
||||
toJson(Object, Boolean) 将对象转json对象,Boolean:是否格式化json,不填时为不格式化。
|
||||
toUnicode(String, Boolean) 将String转换为unicode形式,Boolean:是否转换所有符号,不填时只转换中文及中文符号。
|
||||
$time
|
||||
currTime(String format) 获取当前时间,指定时间格式(默认:yyyy-MM-dd HH:mm:ss)
|
||||
$generateService
|
||||
|
|
|
@ -0,0 +1,22 @@
|
|||
package com.sjhy.plugin.tool;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* ToUnicodeTest 类
|
||||
*
|
||||
* @author czb 2019/11/11 9:43
|
||||
* @version 1.0
|
||||
**/
|
||||
public class ToUnicodeTest {
|
||||
|
||||
@Test
|
||||
public void toUnicode() {
|
||||
GlobalTool tool = GlobalTool.getInstance();
|
||||
String out;
|
||||
System.out.println(out = tool.toUnicode("金融机构,Finance organization{0},!"));
|
||||
Assert.assertEquals("\\u91d1\\u878d\\u673a\\u6784\\uff0cFinance organization{0},\\uff01", out);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue