如何用Java将字符串中的Unicode转义字符替换为实际字符?
解决Unicode转义字符替换问题
好问题!处理字符串中的Unicode转义字符(比如\u0026转&、\u002A转*),我可以帮你完善现有代码,也给你更简洁的实现方案。
方案一:完善你自己的正则匹配实现
你的初始思路是对的,用正则匹配\uXXXX格式的转义字符,然后逐个转换。我们来补全unicodeToString方法和tidy里的替换逻辑:
完整代码
import java.util.regex.Matcher; import java.util.regex.Pattern; public class UnicodeUtils { public static String tidy(String s) { if (s == null || s.isEmpty()) { return s; } // 匹配\u开头的4位十六进制字符 String unicodeCharRegex = "\\\\u[A-Fa-f0-9]{4}"; Pattern p = Pattern.compile(unicodeCharRegex); Matcher m = p.matcher(s); StringBuffer sb = new StringBuffer(); while (m.find()) { String unicodeStr = m.group(); String actualChar = unicodeToString(unicodeStr); // 用appendReplacement避免替换时的转义问题 m.appendReplacement(sb, Matcher.quoteReplacement(actualChar)); } m.appendTail(sb); return sb.toString(); } private static String unicodeToString(String u) { // 去掉前缀\u,剩下4位十六进制字符串 String hex = u.substring(2); try { // 十六进制转成int,再转成char int codePoint = Integer.parseInt(hex, 16); return String.valueOf((char) codePoint); } catch (NumberFormatException e) { // 如果格式不合法,返回原字符串避免崩溃 return u; } } // 测试示例 public static void main(String[] args) { String sample = "Cooking \\u0026 Baking Needs \\u002A"; System.out.println(tidy(sample)); // 输出:Cooking & Baking Needs * } }
关键细节说明
- 用
StringBuffer配合Matcher.appendReplacement和appendTail是高效替换的标准做法,避免多次字符串拼接的性能损耗。 Matcher.quoteReplacement确保替换的特殊字符(比如$)不会被当成正则分组引用处理。- 在
unicodeToString里加了异常捕获,遇到格式不正确的Unicode转义时会返回原字符串,避免程序崩溃。
方案二:用Java原生工具类简化实现
如果你不想自己写正则和转换逻辑,Java的java.util.Properties类自带解析Unicode转义的能力,我们可以直接利用:
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Properties; public class UnicodeUtils { public static String tidy(String s) { if (s == null || s.isEmpty()) { return s; } Properties props = new Properties(); // 构造符合Properties格式的输入:key=value String propStr = "temp=" + s; try (InputStream is = new ByteArrayInputStream(propStr.getBytes(StandardCharsets.ISO_8859_1))) { props.load(is); return props.getProperty("temp"); } catch (IOException e) { // 异常情况下返回原字符串 return s; } } // 测试示例 public static void main(String[] args) { String sample = "Cooking \\u0026 Baking Needs \\u002A"; System.out.println(tidy(sample)); // 输出:Cooking & Baking Needs * } }
这个方法的好处是不用自己处理正则和转换逻辑,Java原生类已经帮我们覆盖了所有合法的Unicode转义场景。
方案三:第三方库快速实现(Apache Commons Text)
如果你的项目已经依赖了Apache Commons Text,直接用StringEscapeUtils.unescapeJava方法就能一行搞定,还能同时处理其他Java转义字符(比如\n、\t):
import org.apache.commons.text.StringEscapeUtils; public class UnicodeUtils { public static String tidy(String s) { if (s == null) { return null; } return StringEscapeUtils.unescapeJava(s); } }
内容的提问来源于stack exchange,提问作者quarks
相关产品推荐
相关产品推荐

