将 Unicode 编码替换成汉字

可以使用 Java 语言中的正则表达式和字符串替换方法实现这个转换功能,代码如下所示:

String input = "## added by mgr on 2019-12-25\n" + "##\\u662F\\u5426\\u5F00\\u542F\\u9A8C\\u8BC1\\u7801\n" + "auth.client.openCaptcha=false\n"
    + "\n" + "##\\u4E0D\\u9700\\u8981\\u62E6\\u622A\\u7684 uri\n"
    + "#auth.client.anonUri=/static/**,/captcha/**,/authorize,/accessToken,/index,/third/**,/pwd/**,/sys/forgotPwd**,/sys/forgotPwd/**,/dict/**\n"
    + "auth.client.anonUri=/static/**,/captcha/**,/authorize,/accessToken,/,/index,/index/**,/reg/**,/pwd,/pwd/**,/mb/**,/loginpwd,/loginpwd/**,/user/registered,/sys/forgotPwd/**,/dict/**,/vldCode/**,/getLoginConfig,/heartbeat\n"
    + "##\\u9700\\u8981\\u767B\\u5F55\\u540E\\u8BBF\\u95EE\\u7684\\u5730\\u5740\n" + "auth.client.userUrl=/xxx/**\n" + "\n"
    + "#############\\u5BA2\\u6237\\u7AEFCookie\\u914D\\u7F6E#############\n" + "#cookie\\u5171\\u4EAB\\u57DF\n"
    + "auth.client.cookie.domain=\n" + "#cookie\\u662F\\u5426https\n" + "auth.client.cookie.secure=false\n"
    + "#cookie\\u5171\\u4EAB\\u8DEF\\u5F84\n" + "auth.client.cookie.path=/\n" + "#cookie\\u9ED8\\u8BA4\\u8FC7\\u671F\\u65F6\\u95F4(\\u79D2)\n"
    + "auth.client.cookie.timeout=3600";
String regex = "\\\\u([0-9a-fA-F]{4})";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
    String unicode = matcher.group(1);
    char ch = (char)Integer.parseInt(unicode, 16);
    matcher.appendReplacement(sb, String.valueOf(ch));
}
matcher.appendTail(sb);
String output = sb.toString();
System.out.println(output);

这里使用正则表达式 “\u([0-9a-fA-F]{4})” 匹配输入字符串中的 Unicode 编码部分,然后将 Unicode 编码转换成汉字,最后通过字符串替换方法实现将 Unicode 编码替换成汉字的功能。

执行结果

## added by mgr on 2019-12-25
##是否开启验证码
auth.client.openCaptcha=false

##不需要拦截的 uri
#auth.client.anonUri=/static/**,/captcha/**,/authorize,/accessToken,/index,/third/**,/pwd/**,/sys/forgotPwd**,/sys/forgotPwd/**,/dict/**
auth.client.anonUri=/static/**,/captcha/**,/authorize,/accessToken,/,/index,/index/**,/reg/**,/pwd,/pwd/**,/mb/**,/loginpwd,/loginpwd/**,/user/registered,/sys/forgotPwd/**,/dict/**,/vldCode/**,/getLoginConfig,/heartbeat
##需要登录后访问的地址
auth.client.userUrl=/xxx/**

你可能感兴趣的:(java,笔记,正则表达式)