簡體   English   中英

是否有Java實用程序來驗證字符串是否是有效的HTML轉義字符?

[英]Is there a Java utility to verify if a string is a valid HTML escape character?

我想要一個以下格式的方法:

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

我無法找到任何可以做到這一點的東西 - 是否有任何實用程序可以做到這一點? 如果沒有,有什么聰明的方法嗎?

不確定這是否是一個完美的解決方案,但您可以使用Apache Commons Lang:

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

你可能想看看Apache commons StringUtils: http ://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringEscapeUtils.html#unescapeHtml( java.lang.String

你可以用unescapeHtml做某事。 喜歡:

String input = "A";
String unescaped = StringEscapeUtils.unescapeHtml(input);
boolean containsValidEscape = !input.equals(a);
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

這應該是你想要的方法:

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上找到正則表達式的來源

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM