从JavaScript转义的Unicode转换为Java Unicode [英] Conversion from javascript-escaped Unicode to Java Unicode

查看:145
本文介绍了从JavaScript转义的Unicode转换为Java Unicode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过HTTP请求传递的查询字符串,其中包含此字符:



%u54E6



我想生成一个包含实际汉字的字符串,所以我可以在应用程序的不同部分使用它,我试过使用这个代码:

  String foo =%u54E6; 
String ufoo = new String(foo.replaceAll(%u([a-zA-Z0-9] {4}),\\+u $ 1));
System.out.println(ufoo:+ ufoo);

不幸的是,我所获得的是'u54E6'打印到控制台的值,而不是中文字符。



有没有一种简单的方式将原始字符串转换为Java中的Unicode字符?

解决方案

您正在尝试在运行时使用 \u 转义。这些只是编译时间。相反,您应该可以执行以下操作:

  String foo =%u54E6; 
模式p = Pattern.compile(%u([a-zA-Z0-9] {4}));
Matcher m = p.matcher(foo);
StringBuffer sb = new StringBuffer();
while(m.find()){
m.appendReplacement(sb,
String.valueOf((char)Integer.parseInt(m.group(1),16)));
}
m.appendTail(sb);
System.out.println(sb.toString());


I have a query string passed in through an HTTP request that has this character in it:

%u54E6

And I'd like to generate a string that contains the actual Chinese character so I can use it in a different part of the application, I've tried using this code:

String foo = "%u54E6";
String ufoo = new String(foo.replaceAll("%u([a-zA-Z0-9]{4})", "\\" + "u$1"));
System.out.println("ufoo: " + ufoo);

Unfortunately, all I'm getting is 'u54E6' printed to the console for the value, instead of the Chinese character.

Is there an easy way to convert the original string to a Unicode character in Java?

解决方案

You're trying to use \u escapes at run time. These are compile-time only. Instead, you should be able to do something like:

String foo = "%u54E6";
Pattern p = Pattern.compile("%u([a-zA-Z0-9]{4})");
Matcher m = p.matcher(foo);
StringBuffer sb = new StringBuffer();
while (m.find()) {
  m.appendReplacement(sb,
      String.valueOf((char) Integer.parseInt(m.group(1), 16)));
}
m.appendTail(sb);
System.out.println(sb.toString());

这篇关于从JavaScript转义的Unicode转换为Java Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆