您的位置:首页 > 编程语言 > Java开发

Decode a string in Java

2015-12-30 17:18 375 查看
java中decode字符串:

public class Utils {

private static Pattern validStandard      = Pattern.compile("%([0-9A-Fa-f]{2})");
private static Pattern choppedStandard    = Pattern.compile("%[0-9A-Fa-f]{0,1}$");
private static Pattern validNonStandard   = Pattern.compile("%u([0-9A-Fa-f][0-9A-Fa-f])([0-9A-Fa-f][0-9A-Fa-f])");
private static Pattern choppedNonStandard = Pattern.compile("%u[0-9A-Fa-f]{0,3}$");

public static String resilientUrlDecode(String input) {
String cookedInput = input;

if (cookedInput.indexOf('%') > -1) {
// Transform all existing UTF-8 standard into UTF-16 standard.
cookedInput = validStandard.matcher(cookedInput).replaceAll("%00%$1");

// Discard chopped encoded char at the end of the line (there is no way to know what it was)
cookedInput = choppedStandard.matcher(cookedInput).replaceAll("");

// Handle non standard (rejected by W3C) encoding that is used anyway by some
// See: http://stackoverflow.com/a/5408655/114196 if (cookedInput.contains("%u")) {
// Transform all existing non standard into UTF-16 standard.
cookedInput = validNonStandard.matcher(cookedInput).replaceAll("%$1%$2");

// Discard chopped encoded char at the end of the line
cookedInput = choppedNonStandard.matcher(cookedInput).replaceAll("");
}
}

try {
return URLDecoder.decode(cookedInput,"UTF-16");
} catch (UnsupportedEncodingException e) {
// Will never happen because the encoding is hardcoded
return null;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: