Java Regex String Replace HTML removeTag(String tagname, String xmlstring)

Here you can find the source of removeTag(String tagname, String xmlstring)

Description

Replaces a tag given by a tagname in an xmlstring.

License

Apache License

Parameter

Parameter Description
tagname Name of the tag to be removed
xmlstring XmlString to be modified

Return

modified XmlString

Declaration

public static String removeTag(String tagname, String xmlstring) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**//w w w.j  a  v a 2 s. c o  m
     * A static threadsafe map which contains compiled Regex Patterns.
     */
    private static Map<String, Pattern> patterns = new ConcurrentHashMap<String, Pattern>();

    /**
     * Replaces a tag given by a tagname in an xmlstring.
     * 
     * @param tagname Name of the tag to be removed
     * @param xmlstring XmlString to be modified
     * @return modified XmlString
     */
    public static String removeTag(String tagname, String xmlstring) {
        if (!patterns.containsKey(tagname)) {
            String regex = "(\\<" + tagname + ">.+?\\</" + tagname + ">)";
            Pattern pattern = Pattern.compile(regex, Pattern.DOTALL | Pattern.MULTILINE);
            patterns.put(tagname, pattern);
        }

        Matcher matcher = patterns.get(tagname).matcher(xmlstring);
        if (matcher.find()) {
            xmlstring = matcher.replaceAll("");
        }

        return xmlstring;
    }
}

Related

  1. removeAllHtmlTag(String str)
  2. removeAllTags(String html)
  3. removeAllTags(String htmlText)
  4. removeAllTags(String input)
  5. removeTag(String text)
  6. removeTags(String html)
  7. removeTags(String input, List knownTagList)
  8. removeTags(String string)