Maison Java javaDidacticiel balises HTML de filtre d'expression régulière Java

balises HTML de filtre d'expression régulière Java

Jun 26, 2017 am 11:12 AM
html java 正则 表达式 过滤

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

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 '<':  

                filtered.append("<");   break;   case '>':   

                filtered.append(">");   break;   case '"':   

                filtered.append(""");   break;   case '&':   

                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 '>':   

                    flag = true;   break;   case '<':  

                    flag = true;   break;   case '"':  

                    flag = true;   break;   case '&':  

                    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();   

    }   

}

Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Article chaud

Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD
Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Article chaud

Combien de temps faut-il pour battre Split Fiction?
3 Il y a quelques semaines By DDD
Repo: Comment relancer ses coéquipiers
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: Comment obtenir des graines géantes
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
1 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Tags d'article chaud

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Tableau imbriqué en HTML Tableau imbriqué en HTML Sep 04, 2024 pm 04:49 PM

Tableau imbriqué en HTML

Bordure de tableau en HTML Bordure de tableau en HTML Sep 04, 2024 pm 04:49 PM

Bordure de tableau en HTML

Marge gauche HTML Marge gauche HTML Sep 04, 2024 pm 04:48 PM

Marge gauche HTML

Disposition du tableau HTML Disposition du tableau HTML Sep 04, 2024 pm 04:54 PM

Disposition du tableau HTML

Déplacer du texte en HTML Déplacer du texte en HTML Sep 04, 2024 pm 04:45 PM

Déplacer du texte en HTML

Bouton HTML onclick Bouton HTML onclick Sep 04, 2024 pm 04:49 PM

Bouton HTML onclick

Comment analysez-vous et traitez-vous HTML / XML dans PHP? Comment analysez-vous et traitez-vous HTML / XML dans PHP? Feb 07, 2025 am 11:57 AM

Comment analysez-vous et traitez-vous HTML / XML dans PHP?

Break or Return of Java 8 Stream Forach? Break or Return of Java 8 Stream Forach? Feb 07, 2025 pm 12:09 PM

Break or Return of Java 8 Stream Forach?

See all articles