java - 是否有 Java 实用程序来验证字符串是否是有效的 HTML 转义字符?

标签 java html escaping html-escape-characters

我想要以下格式的方法:

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

关于java - 是否有 Java 实用程序来验证字符串是否是有效的 HTML 转义字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13975199/

相关文章:

java - java中如何拦截特定接口(interface)?

php - 在 cookie 中存储多个二进制值

html - 使 Bootstrap 表单内联并更好地布局

windows - 使用 Windows 命令行将多行环境变量回显到文本文件

postgresql - SQL 中有转义变量的机制吗?

java - 为什么我的 Properties 对象在我执行 get 时会忽略默认值?

java - 如何检查网页上元素的存在?

c# - 如何在 razor foreach 中使用 html 和 escape razor?

java - 如何在 jersey WriterInterceptor 实现中获取 @interface 参数

html - 如何使用 CSS 在没有 div 的情况下使按钮居中