Java HTML Jsoup Element replaceHtml(Node element)

Here you can find the source of replaceHtml(Node element)

Description

replace Html

License

Open Source License

Declaration

private static void replaceHtml(Node element) 

Method Source Code

//package com.java2s;
/**//from   www  .  java 2 s.c o m
 * This file is part of mycollab-core.
 *
 * mycollab-core is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * mycollab-core is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with mycollab-core.  If not, see <http://www.gnu.org/licenses/>.
 */

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;

import java.util.List;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static void replaceHtml(Node element) {
        List<Node> elements = element.childNodes();
        Pattern compile = Pattern.compile("(?:https?|ftps?)://[\\w/%.-][/\\??\\w=?\\w?/%.-]?[/\\?&\\w=?\\w?/%.-]*");
        for (int i = elements.size() - 1; i >= 0; i--) {
            Node node = elements.get(i);
            if (node instanceof TextNode) {
                String value = ((TextNode) node).text();
                Matcher matcher = compile.matcher(value);
                if (matcher.find()) {
                    value = value.replaceAll(
                            "(?:https?|ftps?)://[\\w/%.-][/\\??\\w=?\\w?/%.-]?[/\\?&\\w=?\\w?/%.-]*",
                            "<a href=\"$0\" target=\"_blank\">$0</a>");
                    Document newDoc = Jsoup.parse(value);
                    List<Node> childs = newDoc.body().childNodes();
                    for (int j = 0; j < childs.size(); j++) {
                        Node childNode = childs.get(j).clone();
                        node.before(childNode);
                    }
                    node.remove();
                }
            }
        }
    }
}

Related

  1. markAll(Elements tags)
  2. markChildren(Element tag, final String color)
  3. printNode(Element root)
  4. processCheck(Element ele, Element parent, String dict)
  5. randomElement()
  6. sameTagElNums(Element e)
  7. setAttribute(Element e, String key, String value)
  8. stripAttribute(Element body, String attribute)
  9. stripEmptyDivs(Element body)