JAVA通过正则匹配html里面body标签的内容,具体代码如下,如果要取得html代码中body里面的内容 不包含body标签,直接调用 removeBody以上就是JAVA通过正则匹配html里面body标签的内容所有内容。
- /**
- * 获取html中body的内容 包含body标签
- * @param htmlStr html代码
- * @return
- */
- public static String getBody(String htmlStr){
- String pattern = "<body[^>]*>([\\s\\S]*)<\\/body>";
- Pattern p_body = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
- Matcher m_body = p_body.matcher(htmlStr);
- if (m_body.find()){
- return m_body.group();
- }
- return htmlStr;
- }
- /**
- * 取到html中body里面的内容 不包含body标签
- * @param htmlStr
- * @return
- */
- public static String removeBody(String htmlStr){
- /**
- * 获取html代码中body标签里的内容
- */
- htmlStr=getBody(htmlStr);
- //body开头标签
- String bodyEx_start = "<body[^>]*>";
- //body结尾标签
- String bodyEx_end = "<\\/body>";
- Pattern p_script = Pattern.compile(bodyEx_start, Pattern.CASE_INSENSITIVE);
- Matcher m_script = p_script.matcher(htmlStr);
- htmlStr = m_script.replaceAll(""); // 过滤script标签
- Pattern p_style = Pattern.compile(bodyEx_end, Pattern.CASE_INSENSITIVE);
- Matcher m_style = p_style.matcher(htmlStr);
- htmlStr = m_style.replaceAll(""); // 过滤style标签
- return htmlStr;
- }
"小礼物走一走,来肥宅自学平台支持我"
评论区
共条评论
- 这篇文章还没有收到评论,赶紧来抢沙发吧~
首页上页1下页尾页