Skip to content

Commit d0f72c0

Browse files
makejavasgitee-org
authored andcommitted
!5 $tool工具中增加toUnicode(String[, Boolean])方法,用于将字符串转换为UNICODE编码。
Merge pull request !5 from czb/master
2 parents 1aae2a0 + d593f13 commit d0f72c0

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

src/main/java/com/sjhy/plugin/tool/GlobalTool.java

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,54 @@ public String toJson(Object obj, Boolean format) {
277277
}
278278
}
279279

280+
// 中文及中文符号正则表达式
281+
public static final String CHINESE_REGEX = "[\u4e00-\u9fa5–—‘’“”…、。〈〉《》「」『』【】〔〕!(),.:;?]";
282+
283+
/**
284+
* 字符串转unicode编码(默认只转换CHINESE_REGEX匹配到的字符)
285+
* @param str 字符串
286+
* @return 转码后的字符串
287+
*/
288+
public String toUnicode(String str) {
289+
return toUnicode(str, false);
290+
}
291+
292+
/**
293+
* 字符串转unicode编码
294+
* @param str 字符串
295+
* @param transAll true转换所有字符,false只转换CHINESE_REGEX匹配到的字符
296+
* @return 转码后的字符串
297+
*/
298+
public String toUnicode(String str, Boolean transAll) {
299+
if (null == str) {
300+
return null;
301+
}
302+
if (str.length() <= 0) {
303+
return null;
304+
}
305+
if (null == transAll) {
306+
transAll = false;
307+
}
308+
309+
StringBuffer sb = new StringBuffer();
310+
if (transAll) {
311+
for (char c : str.toCharArray()) {
312+
sb.append(String.format("\\u%04x", (int) c));
313+
}
314+
} else {
315+
for (char c : str.toCharArray()) {
316+
// 中文范围
317+
if (String.valueOf(c).matches(CHINESE_REGEX)) {
318+
sb.append(String.format("\\u%04x", (int) c));
319+
} else {
320+
sb.append(c);
321+
}
322+
}
323+
}
324+
325+
return sb.toString();
326+
}
327+
280328
/**
281329
* 远程调用服务
282330
*

src/main/resources/description/templateDescription.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@
5757
service(String serviceName, Object... param)远程服务调用
5858
parseJson(String) 将字符串转Map对象
5959
toJson(Object, Boolean) 将对象转json对象,Boolean:是否格式化json,不填时为不格式化。
60+
toUnicode(String, Boolean) 将String转换为unicode形式,Boolean:是否转换所有符号,不填时只转换中文及中文符号。
6061
$time
6162
currTime(String format) 获取当前时间,指定时间格式(默认:yyyy-MM-dd HH:mm:ss)
6263
$generateService
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.sjhy.plugin.tool;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
/**
7+
* ToUnicodeTest 类
8+
*
9+
* @author czb 2019/11/11 9:43
10+
* @version 1.0
11+
**/
12+
public class ToUnicodeTest {
13+
14+
@Test
15+
public void toUnicode() {
16+
GlobalTool tool = GlobalTool.getInstance();
17+
String out;
18+
System.out.println(out = tool.toUnicode("金融机构,Finance organization{0},!"));
19+
Assert.assertEquals("\\u91d1\\u878d\\u673a\\u6784\\uff0cFinance organization{0},\\uff01", out);
20+
}
21+
22+
}

0 commit comments

Comments
 (0)