2016-09-08 68 views

回答

1

你可以用這樣的一段代碼:

String str = myString.split(" ")[0]; 
str = str.replace("\\",""); 
String[] arr = str.split("u"); 
String text = ""; 
for(int i = 1; i < arr.length; i++){ 
    int hexVal = Integer.parseInt(arr[i], 16); 
    text += (char)hexVal; 
} 

,或者您可以使用Apache Commons Lang中:

import org.apache.commons.lang.StringEscapeUtils; 

@Test 
public void testUnescapeJava() { 
    String sJava="\\u0048\\u0065\\u006C\\u006C\\u006F"; 
    System.out.println("StringEscapeUtils.unescapeJava(sJava):\n" + StringEscapeUtils.unescapeJava(sJava)); 
} 


output: 
StringEscapeUtils.unescapeJava(sJava): 
Hello 
1

您可以使用UTF_16字符集解析字節例如

replaceCharEscapes("\\u0043:\\\\u0050\\u0072\\u006f\\u0067\\u0072\\u0061\\u006ds") 

回報C:\Programs

byte[] data = {0x06, 0x28}; 
String string = new String(data, StandardCharsets.UTF_16); 

你可以使用正則表達式

private static Pattern ESCAPE_PATTERN = Pattern.compile("\\\\u([0-9a-fA-F]{2})([0-9a-fA-F]{2})"); 

public static String replaceCharEscapes(String input) { 
    Matcher m = ESCAPE_PATTERN.matcher(input); 
    if (!m.find()) { 
     return input; 
    } 
    StringBuilder outputBuilder = new StringBuilder(input.subSequence(0, m.start())); 
    int lastEnd = m.end(); 
    outputBuilder.append(getChar(m)); 

    while (m.find()) { 
     outputBuilder.append(input.subSequence(lastEnd, m.start())) 
       .append(getChar(m)); 
     lastEnd = m.end(); 
    } 

    if (lastEnd != input.length()) { 
     outputBuilder.append(input.subSequence(lastEnd, input.length())); 
    } 

    return outputBuilder.toString(); 
} 

private static String getChar(Matcher m) { 
    return new String(new byte[] { 
     Byte.parseByte(m.group(1), 16), 
     Byte.parseByte(m.group(2), 16), 
    }); 
} 

例如找到逃逸

相關問題