是否有Java实用程序可以验证字符串是否为有效的HTML逃生字符



我想要以下格式的方法:

public boolean isValidHtmlEscapeCode(String string);

用法是:

isValidHtmlEscapeCode("A") == false
isValidHtmlEscapeCode("ש") == true // Valid unicode character
isValidHtmlEscapeCode("ש") == true // same as 1513 but in HEX
isValidHtmlEscapeCode("�") == false // Invalid unicode character

我找不到任何可以做到的东西 - 有没有做到这一点的实用程序?如果没有,有什么明智的方法吗?

public static boolean isValidHtmlEscapeCode(String string) {
    if (string == null) {
        return false;
    }
    Pattern p = Pattern
            .compile("&(?:#x([0-9a-fA-F]+)|#([0-9]+)|([0-9A-Za-z]+));");
    Matcher m = p.matcher(string);
    if (m.find()) {
        int codePoint = -1;
        String entity = null;
        try {
            if ((entity = m.group(1)) != null) {
                if (entity.length() > 6) {
                    return false;
                }
                codePoint = Integer.parseInt(entity, 16);
            } else if ((entity = m.group(2)) != null) {
                if (entity.length() > 7) {
                    return false;
                }
                codePoint = Integer.parseInt(entity, 10);
            } else if ((entity = m.group(3)) != null) {
                return namedEntities.contains(entity);
            }
            return 0x00 <= codePoint && codePoint < 0xd800
                    || 0xdfff < codePoint && codePoint <= 0x10FFFF;
        } catch (NumberFormatException e) {
            return false;
        }
    } else {
        return false;
    }
}

这是一组命名实体http://pastebin.com/xzzmydjf

您可能想看看Apache Commons stringutils:http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/stringescapeutils.html#un.unescapehtml(java.lang.string)

使用UNESCAPEHTML,您可以做STH。喜欢:

String input = "A";
String unescaped = StringEscapeUtils.unescapeHtml(input);
boolean containsValidEscape = !input.equals(a);

不确定这是一个完美的解决方案,但是您可以使用apache commons lang:

try {
    return StringEscapeUtils.unescapeHtml4(code).length() < code.length();
} catch (IllegalArgumentException e) {
    return false;
}

这应该是您想要的方法:

public static boolean isValidHtmlEscapeCode(String string) {
String temp = "";
try {
    temp = StringEscapeUtils.unescapeHtml3(string);
} catch (IllegalArgumentException e) {
    return false;
}
return !string.equals(temp);
}

尝试使用正则表达式匹配:

public boolean isValidHtmlEscapeCode(String string) {
    return string.matches("&;#([0-9]{1,4}|x[0-9a-fA-F]{1,4});");
}

或保存某些处理周期,您可以重复使用正则以进行多个比较:

Pattern pattern = Pattern.compile("&;#([0-9]{1,4}|x[0-9a-fA-F]{1,4});");
public boolean isValidHtmlEscapeCode(String string) {
    return pattern.matches(string);
}

可以在rexlib.com

上找到正则态度的来源。

最新更新