2015-10-06 93 views
0

它在Android上,并且需要在加载到WebView之前修复html。如何替换超链接中的某些文本

通常它可以通过

(<a[^>]+>)(.+?)(<\/a>) 

做才能获得组$ 1,则替换文本。

如果< a> tag内有其他未知的孩子会怎么样? 下面的例子有< a> < p> ...文本</p> </a>,但< p>可能不知道。

真的是它只需要替换元素内任何子元素的文本元素的内容。

<a href="http://news.newsletter.com/" target="_blank"> 
    <p><img alt=“Socialbook" border="0" height="50" 
    src="http://news.newsletter.com/images/socialbook.gif" width="62"> 
    THIS IS THE TEXT NEEDED TO REPLACE<p> 
</a> 

这可以在JAVA内完成,还是必须在WebView的javascript内完成?

+0

$ regex =“〜> [\ w \ s] +?<〜”; – jessica

+0

不要使用正则表达式。 – njzk2

回答

2

您可以使用任何Java html解析器。例如。 JSoup

String html = "<html><head><title>First parse</title></head>" 
    + "<body><a href="..."><p>Parsed HTML into a doc.</p></a></body></html>"; 
Document doc = Jsoup.parse(html); 
Elements links = doc.select("a"); 
for (Element link : links) 
    link.text("~" + link.text() + "~"); 

Element API文档。

+0

好的建议,是否有示例显示如何将更改应用到所有文本内容元素? – lannyf

+0

在http://stackoverflow.com/questions/30425002/how-i-can-replace-text-in-the-each-tag-using-jsoup发现了一个示例,在这里复制。 Element entry = doc.select(“div”)。first(); 元素tags = entry.getAllElements(); (子节点child:tag.childNodes()){ if(child instanceof TextNode &&!((TextNode)child).isBlank()){0} ); //(textNode)child).text(“word”); //文本 ((TextNode)child).text //替换为文字 } } } – lannyf

相关问题