StringEscapeUtils find out if string is escaped

2019-06-04 01:27发布

问题:

I've been using StringEscapeUtils.escapeHTML to escape URLs. Is there something similar to find out if the string is already escaped?

回答1:

Not that I know of, but it is pretty easy to do one yourself:

public boolean isEscaped(String url) {
    return !url.equals(StringEscapeUtils.unEscapeHTML(url));
}

Note that deciding if a random string is escaped or not is impossible as @themel notes, you can get a lot of false positives if you try this with random strings. However I'm assuming that you at least have some control over what your strings look like here.



回答2:

This is impossible in principle, since every escaped string is at the same time an unescaped string, e.g. "a>b" could be both an escaped version of "a>b" or simply the literal string "a>b" before escaping.



回答3:

If you are just trying to escape any string until you get pure HTML tags try this recursive method:

    public static String unescapeHtml(String string) {
    if (org.apache.commons.lang3.StringUtils.isBlank(string)) {
        return "";
    }
    String unescapedString = StringEscapeUtils.unescapeHtml(string);
    return string.equals(StringEscapeUtils.unescapeHtml(string)) ? unescapedString : unescapeHtml(unescapedString);
}