Convert from javascript-escaped Unicode to Java Unicode

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

% u54E6

And I would like to create a string containing the actual Chinese character, so I can use it in another part of the application, I 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 get is "u54E6" printed on the console for a value instead of a Chinese character.

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

+1
java encoding unicode
source share
1 answer

You are trying to use \u screens at runtime. This is only compilation time. Instead, you can 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()); 
+3
source share

All Articles