如何查找String是否包含html数据?

Joe*_*Joe 21 html java

如何查找字符串是否包含HTML数据?用户通过Web界面提供输入,很可能他可以使用简单文本或使用HTML格式.

Dav*_*ett 17

我知道这是一个老问题,但我遇到了它,并且正在寻找更全面的东西,可以检测HTML实体之类的东西,并忽略<和>符号的其他用途.我想出了下面这个运作良好的课程.

您可以在http://ideone.com/HakdHo上直播

我还通过一系列JUnit测试将其上传到GitHub.

package org.github;

/**
 * Detect HTML markup in a string
 * This will detect tags or entities
 *
 * @author dbennett455@gmail.com - David H. Bennett
 *
 */

import java.util.regex.Pattern;

public class DetectHtml
{
    // adapted from post by Phil Haack and modified to match better
    public final static String tagStart=
        "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)\\>";
    public final static String tagEnd=
        "\\</\\w+\\>";
    public final static String tagSelfClosing=
        "\\<\\w+((\\s+\\w+(\\s*\\=\\s*(?:\".*?\"|'.*?'|[^'\"\\>\\s]+))?)+\\s*|\\s*)/\\>";
    public final static String htmlEntity=
        "&[a-zA-Z][a-zA-Z0-9]+;";
    public final static Pattern htmlPattern=Pattern.compile(
      "("+tagStart+".*"+tagEnd+")|("+tagSelfClosing+")|("+htmlEntity+")",
      Pattern.DOTALL
    );

    /**
     * Will return true if s contains HTML markup tags or entities.
     *
     * @param s String to test
     * @return true if string contains HTML
     */
    public static boolean isHtml(String s) {
        boolean ret=false;
        if (s != null) {
            ret=htmlPattern.matcher(s).find();
        }
        return ret;
    }

}
Run Code Online (Sandbox Code Playgroud)


Tom*_*len 3

您可以使用正则表达式来搜索 HTML 标签。