在JSOUP中使用Regex突出显示android

时间:2011-12-07 06:37:17

标签: android html-parsing jsoup

我正在使用JSoup解析器来查找html文档的特定部分(由regex定义),并通过将找到的字符串包装在<span>标记中来突出显示它。这是我的代码突出显示 -

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

它确实有效但标记<span>在webview中可见。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

看起来没有人知道。这是我提出的一些代码。缓慢而低效但无论如何都有效。建议被接受:)

此类可用于使用正则表达式突出显示任何html。

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;
        }
    }
}

你必须调用这两种方法来获得突出显示的html -

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

这将突出显示与正则表达式(abc)|(def)*匹配的所有内容。 您可以通过modifying buildRegexFromQuery()函数更改您希望构建正则表达式的方式。