Highlighting using Regex in JSOUP for android

点点圈 提交于 2021-01-28 05:13:49

问题


I am using JSoup parser to find particular parts of a html document (defined by regex) and highlight it by wrapping the found string in <span> tag. Here is my code that does the highlighting -

public String highlightRegex() {
Document doc = Jsoup.parse(htmlContent);

        NodeTraversor nd  = new NodeTraversor(new NodeVisitor() {

            @Override
            public void tail(Node node, int depth) {
                if (node instanceof Element) {

                    Element elem = (Element) node;

                    StringBuffer obtainedText;
                    for(Element tn : elem.getElementsMatchingOwnText(pat)) {

                        Log.e("HELLO", tn.baseUri());
                        Log.e("HELLO", tn.text());
                        obtainedText = new StringBuffer(tn.ownText());
                        mat = pat.matcher(obtainedText.toString());
                        int nextStart = 0;
                        while(mat.find(nextStart)) {
                            obtainedText = obtainedText.replace(mat.start(), mat.end(), "<span>" + mat.group() + "</span>");
                            nextStart = mat.end() + 1;
                        }
                        tn.text(obtainedText.toString());
                        Log.e("HELLO" , "AFTER:" + tn.text());

                    }
                }
            }

            @Override
            public void head(Node node, int depth) {        
            }
        });

        nd.traverse(doc.body());
        return doc.toString();
    }

It does work but the tag <span> is visible inside the webview. What am I doing wrong?


回答1:


Looks like no one knows. Here's some code that i've come up with. Slow and inefficient but works anyway. Suggestions are accepted :)

This class can be used to highlight any html using a regex.

public class Highlighter {

    private String regex;
    private String htmlContent;
    Pattern pat;
    Matcher mat;


    public Highlighter(String searchString, String htmlString) {
        regex = buildRegexFromQuery(searchString);
        htmlContent = htmlString;
        pat = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
    }

    public String getHighlightedHtml() {

        Document doc = Jsoup.parse(htmlContent);

        final List<TextNode> nodesToChange = new ArrayList<TextNode>();

        NodeTraversor nd  = new NodeTraversor(new NodeVisitor() {

            @Override
            public void tail(Node node, int depth) {
                if (node instanceof TextNode) {
                    TextNode textNode = (TextNode) node;
                    String text = textNode.getWholeText();

                    mat = pat.matcher(text);

                    if(mat.find()) {
                        nodesToChange.add(textNode);
                    }
                }
            }

            @Override
            public void head(Node node, int depth) {        
            }
        });

        nd.traverse(doc.body());

        for (TextNode textNode : nodesToChange) {
            Node newNode = buildElementForText(textNode);
            textNode.replaceWith(newNode);
        }
        return doc.toString();
    }

    private static String buildRegexFromQuery(String queryString) {
        String regex = "";
        String queryToConvert = queryString;

        /* Clean up query */

        queryToConvert = queryToConvert.replaceAll("[\\p{Punct}]*", " ");
        queryToConvert = queryToConvert.replaceAll("[\\s]*", " ");

        String[] regexArray = queryString.split(" ");

        regex = "(";
        for(int i = 0; i < regexArray.length - 1; i++) {
            String item = regexArray[i];
            regex += "(\\b)" + item + "(\\b)|";
        }

        regex += "(\\b)" + regexArray[regexArray.length - 1] + "[a-zA-Z0-9]*?(\\b))";
        return regex;
    }

    private Node buildElementForText(TextNode textNode) {
        String text = textNode.getWholeText().trim();

        ArrayList<MatchedWord> matchedWordSet = new ArrayList<MatchedWord>();

        mat = pat.matcher(text);

        while(mat.find()) {
            matchedWordSet.add(new MatchedWord(mat.start(), mat.end()));
        }

        StringBuffer newText = new StringBuffer(text);

        for(int i = matchedWordSet.size() - 1; i >= 0; i-- ) {
            String wordToReplace = newText.substring(matchedWordSet.get(i).start, matchedWordSet.get(i).end);
            wordToReplace = "<b>" + wordToReplace+ "</b>";
            newText = newText.replace(matchedWordSet.get(i).start, matchedWordSet.get(i).end, wordToReplace);       
        }
        return new DataNode(newText.toString(), textNode.baseUri());
    }

    class MatchedWord {
        public int start;
        public int end;

        public MatchedWord(int start, int end) {
            this.start = start;
            this.end = end;
        }
    }
}

you have to call these two methods to get the highlighted html -

Highlighter hl = new Highlighter("abc def", htmlString);
String newhtmlString = hl.getHighlightedHtml();

This will highlight everything that matches the regex (abc)|(def)*. You can change the way you want the regex to be built by modifying buildRegexFromQuery() function.



来源:https://stackoverflow.com/questions/8411362/highlighting-using-regex-in-jsoup-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!