Home Java javaTutorial java uses regular expression to filter html tags

java uses regular expression to filter html tags

Jan 22, 2017 am 11:54 AM

前段时间开发的时候要读取一篇文章的简介内容(也就是前200个字符),使用了隐藏字段,可能有人就要问了,那后台也是可以截取字符的啊,那是因为编辑器里面包含了html标签,所以后台就需要处理html标签的正则表达式,前些天上网搜了下,发现有人写好的一个类,给大家共享下

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 
  
/** 
 * <p> 
 * Title: HTML相关的正则表达式工具类 
 * </p> 
 * <p> 
 * Description: 包括过滤HTML标记,转换HTML标记,替换特定HTML标记 
 * </p> 
 * <p> 
 * Copyright: Copyright (c) 2006 
 * </p> 
 * 
 * @author hejian 
 * @version 1.0 
 * @createtime 2006-10-16 
 */
  
public class HtmlRegexpUtil { 
 private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签 
  
 private final static String regxpForImgTag = "<\\s*img\\s+([^>]*)\\s*>"; // 找出IMG标签 
  
 private final static String regxpForImaTagSrcAttrib = "src=\"([^\"]+)\""; // 找出IMG标签的SRC属性 
  
 /** 
  * 
  */
 public HtmlRegexpUtil() { 
  // TODO Auto-generated constructor stub 
 } 
  
 /** 
  * 
  * 基本功能:替换标记以正常显示 
  * <p> 
  * 
  * @param input 
  * @return String 
  */
 public String replaceTag(String input) { 
  if (!hasSpecialChars(input)) { 
   return input; 
  } 
  StringBuffer filtered = new StringBuffer(input.length()); 
  char c; 
  for (int i = 0; i <= input.length() - 1; i++) { 
   c = input.charAt(i); 
   switch (c) { 
   case &#39;<&#39;: 
    filtered.append("<"); 
    break; 
   case &#39;>&#39;: 
    filtered.append(">"); 
    break; 
   case &#39;"&#39;: 
    filtered.append("""); 
    break; 
   case &#39;&&#39;: 
    filtered.append("&"); 
    break; 
   default: 
    filtered.append(c); 
   } 
  
  } 
  return (filtered.toString()); 
 } 
  
 /** 
  * 
  * 基本功能:判断标记是否存在 
  * <p> 
  * 
  * @param input 
  * @return boolean 
  */
 public boolean hasSpecialChars(String input) { 
  boolean flag = false; 
  if ((input != null) && (input.length() > 0)) { 
   char c; 
   for (int i = 0; i <= input.length() - 1; i++) { 
    c = input.charAt(i); 
    switch (c) { 
    case &#39;>&#39;: 
     flag = true; 
     break; 
    case &#39;<&#39;: 
     flag = true; 
     break; 
    case &#39;"&#39;: 
     flag = true; 
     break; 
    case &#39;&&#39;: 
     flag = true; 
     break; 
    } 
   } 
  } 
  return flag; 
 } 
  
 /** 
  * 
  * 基本功能:过滤所有以"<"开头以">"结尾的标签 
  * <p> 
  * 
  * @param str 
  * @return String 
  */
 public static String filterHtml(String str) { 
  Pattern pattern = Pattern.compile(regxpForHtml); 
  Matcher matcher = pattern.matcher(str); 
  StringBuffer sb = new StringBuffer(); 
  boolean result1 = matcher.find(); 
  while (result1) { 
   matcher.appendReplacement(sb, ""); 
   result1 = matcher.find(); 
  } 
  matcher.appendTail(sb); 
  return sb.toString(); 
 } 
  
 /** 
  * 
  * 基本功能:过滤指定标签 
  * <p> 
  * 
  * @param str 
  * @param tag 
  *   指定标签 
  * @return String 
  */
 public static String fiterHtmlTag(String str, String tag) { 
  String regxp = "<\\s*" + tag + "\\s+([^>]*)\\s*>"; 
  Pattern pattern = Pattern.compile(regxp); 
  Matcher matcher = pattern.matcher(str); 
  StringBuffer sb = new StringBuffer(); 
  boolean result1 = matcher.find(); 
  while (result1) { 
   matcher.appendReplacement(sb, ""); 
   result1 = matcher.find(); 
  } 
  matcher.appendTail(sb); 
  return sb.toString(); 
 } 
  
 /** 
  * 
  * 基本功能:替换指定的标签 
  * <p> 
  * 
  * @param str 
  * @param beforeTag 
  *   要替换的标签 
  * @param tagAttrib 
  *   要替换的标签属性值 
  * @param startTag 
  *   新标签开始标记 
  * @param endTag 
  *   新标签结束标记 
  * @return String 
  * @如:替换img标签的src属性值为[img]属性值[/img] 
  */
 public static String replaceHtmlTag(String str, String beforeTag, 
   String tagAttrib, String startTag, String endTag) { 
  String regxpForTag = "<\\s*" + beforeTag + "\\s+([^>]*)\\s*>"; 
  String regxpForTagAttrib = tagAttrib + "=\"([^\"]+)\""; 
  Pattern patternForTag = Pattern.compile(regxpForTag); 
  Pattern patternForAttrib = Pattern.compile(regxpForTagAttrib); 
  Matcher matcherForTag = patternForTag.matcher(str); 
  StringBuffer sb = new StringBuffer(); 
  boolean result = matcherForTag.find(); 
  while (result) { 
   StringBuffer sbreplace = new StringBuffer(); 
   Matcher matcherForAttrib = patternForAttrib.matcher(matcherForTag 
     .group(1)); 
   if (matcherForAttrib.find()) { 
    matcherForAttrib.appendReplacement(sbreplace, startTag 
      + matcherForAttrib.group(1) + endTag); 
   } 
   matcherForTag.appendReplacement(sb, sbreplace.toString()); 
   result = matcherForTag.find(); 
  } 
  matcherForTag.appendTail(sb); 
  return sb.toString(); 
 } 
}
Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持PHP中文网。

更多java使用正则表达式过滤html标签相关文章请关注PHP中文网!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles