品易云推流 关闭
文章详情页
文章 > JavaScript > js正则匹配html标签中的内容

js正则匹配html标签中的内容

头像

宋雪维

2021-02-18 13:14:506860浏览 · 0收藏 · 0评论

本文教程操作环境:windows7系统、jquery3.2.1版本,DELL G3电脑。

一、正则表达式

是使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。

简单来说,是一种匹配字符串的方法,通过一些特殊符号,实现快速查找、删除、替换某个特定字符串。

二、匹配方法:replace()方法

参数为正则表达式,如果找到匹配时,返回匹配字符串的开始位置,否则,返回-1;不支持全文检索。

三、使用:匹配html标签中的内容

匹配html标签,例如"<p>xxx</p>"这种格式

获取html中的数据并预处理

private static Pattern HTML_TAG_PATTERN = Pattern.compile("<[a-zA-Z]+.*?>([\\s\\S]*?)</[a-zA-Z]*?>");

/**
 * 获取html中的数据
 * @param htmlString
 * @return
 */
public static List<String> getResultsFromHtml(String htmlString) {
    List<String> results = new ArrayList<>();
    // 数据预处理
    htmlString = replaceStyle(removeBrTag(htmlString));
    if (htmlString != null && htmlString.length() > 0) {
        Matcher imageTagMatcher = HTML_TAG_PATTERN.matcher(htmlString);

1、针对多个并列的标签的情况,对应正则表达式中的圆括号括起来的数据

     while (imageTagMatcher.find()) {
            String result = "";
            // group(1)
            result = imageTagMatcher.group(1).trim();

2、针对多个标签嵌套的情况进行处理

  if (result != null && result.length() > 0) {
                result = replaceStartTag(result);
            }

            results.add(result);
        }
    }
    return results;
}

以上就是使用js正则表达式匹配html标签中的内容的方法和实例,大家可以套入代码直接使用哦~

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图