Remover tags HTML de uma String
Pergunta
Existe uma boa maneira de remover HTML de uma seqüência de Java? A regex simples como
replaceAll("\\<.*?>","")
vai funcionar, mas coisas como &
costuma ser convertido corretamente e não-HTML entre os dois colchetes serão removidos (ou seja, o .*?
na regex irá desaparecer).
Solução
Use um analisador de HTML em vez de regex. Isto é simples morto com Jsoup .
public static String html2text(String html) {
return Jsoup.parse(html).text();
}
Jsoup suportes rel="noreferrer"> também remover tags HTML contra um personalizável whitelist, que é muito útil se você quer permitir que somente por exemplo, <b>
, <i>
e <u>
.
Veja também:
Outras dicas
Se você está escrevendo para Android você pode fazer isso ...
android.text.Html.fromHtml(instruction).toString()
Se o usuário entra <b>hey!</b>
, quer <b>hey!</b>
exibição ou hey!
? Se o primeiro, escapar menos thans e ampersands Codifique em HTML (e opcionalmente aspas) e você está bem. Uma modificação ao seu código para implementar a segunda opção seria:
replaceAll("\\<[^>]*>","")
mas você vai ter problemas se o usuário inserir algo mal formado, como <bhey!</b>
.
Você também pode verificar JTidy que irá analisar "sujo" de entrada html, e deve dar-lhe uma maneira para remover as tags, mantendo o texto.
O problema com a tentativa de retirar html é que os navegadores têm analisadores muito branda, mais branda do que qualquer biblioteca você pode encontrar a vontade, por isso mesmo se você fazer o seu melhor para tirar todas as tags (usando o método acima, uma biblioteca DOM substituir, ou JTidy), você vai ainda necessidade de certificar-se de codificar qualquer restantes caracteres especiais HTML para manter seu cofre de saída.
Outra maneira é usar javax.swing.text.html.HTMLEditorKit para extrair o texto.
import java.io.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
public class Html2Text extends HTMLEditorKit.ParserCallback {
StringBuffer s;
public Html2Text() {
}
public void parse(Reader in) throws IOException {
s = new StringBuffer();
ParserDelegator delegator = new ParserDelegator();
// the third parameter is TRUE to ignore charset directive
delegator.parse(in, this, Boolean.TRUE);
}
public void handleText(char[] text, int pos) {
s.append(text);
}
public String getText() {
return s.toString();
}
public static void main(String[] args) {
try {
// the HTML to convert
FileReader in = new FileReader("java-new.html");
Html2Text parser = new Html2Text();
parser.parse(in);
in.close();
System.out.println(parser.getText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
ref: etiquetas Remover HTML a partir de um arquivo para extrair apenas o texto
Eu acho que a maneira mais simples para filtrar as tags de html é:
private static final Pattern REMOVE_TAGS = Pattern.compile("<.+?>");
public static String removeTags(String string) {
if (string == null || string.length() == 0) {
return string;
}
Matcher m = REMOVE_TAGS.matcher(string);
return m.replaceAll("");
}
Também usando muito simples Jericho , e você pode manter alguma da formatação (linha breaks e links, por exemplo).
Source htmlSource = new Source(htmlText);
Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());
Renderer htmlRend = new Renderer(htmlSeg);
System.out.println(htmlRend.toString());
No Android, tente o seguinte:
String result = Html.fromHtml(html).toString();
HTML Escaping é realmente difícil de fazer direita Eu definitivamente sugerir o uso de código de biblioteca para fazer isso, como é muito mais sutil do que você pensa. Confira Apache StringEscapeUtils para uma biblioteca muito bom para lidar com isso em Java.
A resposta aceita de fazer simplesmente Jsoup.parse(html).text()
tem 2 problemas potenciais (com JSoup 1.7.3):
- Ele remove quebras de linha do texto
- Ele converte
<script>
texto<script>
Se você usar isso para proteger contra XSS, isso é um pouco chato. Aqui é a minha melhor chance de uma solução melhorada, usando tanto JSoup e Apache StringEscapeUtils:
// breaks multi-level of escaping, preventing &lt;script&gt; to be rendered as <script>
String replace = input.replace("&", "");
// decode any encoded html, preventing <script> to be rendered as <script>
String html = StringEscapeUtils.unescapeHtml(replace);
// remove all html tags, but maintain line breaks
String clean = Jsoup.clean(html, "", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));
// decode html again to convert character entities back into text
return StringEscapeUtils.unescapeHtml(clean);
Note que o último passo é porque eu preciso usar a saída como texto simples. Se você precisar apenas de saída HTML, então você deve ser capaz de removê-lo.
E aqui é um monte de casos de teste (entrada para a saída):
{"regular string", "regular string"},
{"<a href=\"link\">A link</a>", "A link"},
{"<script src=\"http://evil.url.com\"/>", ""},
{"<script>", ""},
{"&lt;script&gt;", "lt;scriptgt;"}, // best effort
{"\" ' > < \n \\ é å à ü and & preserved", "\" ' > < \n \\ é å à ü and & preserved"}
Se você encontrar uma maneira de torná-lo melhor, por favor me avise.
Você pode querer substituir <br/>
e </p>
tags com novas linhas antes de descascar o HTML para impedir que se torne uma bagunça ilegível como Tim sugere.
A única maneira que eu posso pensar de remover tags HTML, mas deixando não-HTML entre colchetes seria verificação contra um lista de HTML tags de . Algo nesse sentido ...
replaceAll("\\<[\s]*tag[^>]*>","")
caracteres especiais Em seguida, HTML-decodificar como &
. O resultado não deve ser considerada a ser higienizado.
Isso deve funcionar -
Use esta ??p>
text.replaceAll('<.*?>' , " ") -> This will replace all the html tags with a space.
e este
text.replaceAll('&.*?;' , "")-> this will replace all the tags which starts with "&" and ends with ";" like , &, > etc.
A resposta aceita não funcionou para mim para o caso de teste I indicados: o resultado de "uma c" é "um b ou b> c"
.Então, eu usei TagSoup vez. Aqui está uma foto que trabalhava para o meu caso de teste (e um par de outros):
import java.io.IOException;
import java.io.StringReader;
import java.util.logging.Logger;
import org.ccil.cowan.tagsoup.Parser;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Take HTML and give back the text part while dropping the HTML tags.
*
* There is some risk that using TagSoup means we'll permute non-HTML text.
* However, it seems to work the best so far in test cases.
*
* @author dan
* @see <a href="http://home.ccil.org/~cowan/XML/tagsoup/">TagSoup</a>
*/
public class Html2Text2 implements ContentHandler {
private StringBuffer sb;
public Html2Text2() {
}
public void parse(String str) throws IOException, SAXException {
XMLReader reader = new Parser();
reader.setContentHandler(this);
sb = new StringBuffer();
reader.parse(new InputSource(new StringReader(str)));
}
public String getText() {
return sb.toString();
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
for (int idx = 0; idx < length; idx++) {
sb.append(ch[idx+start]);
}
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length)
throws SAXException {
sb.append(ch);
}
// The methods below do not contribute to the text
@Override
public void endDocument() throws SAXException {
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
}
@Override
public void endPrefixMapping(String prefix) throws SAXException {
}
@Override
public void processingInstruction(String target, String data)
throws SAXException {
}
@Override
public void setDocumentLocator(Locator locator) {
}
@Override
public void skippedEntity(String name) throws SAXException {
}
@Override
public void startDocument() throws SAXException {
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes atts) throws SAXException {
}
@Override
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
}
}
Eu sei que isso é velho, mas eu estava apenas trabalhando em um projeto que me obrigado a HTML filtro e isso funcionou bem:
noHTMLString.replaceAll("\\&.*?\\;", "");
em vez disso:
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
Aqui está uma levemente mais aprofundados atualização para tentar lidar com alguma formatação para pausas e listas. Eu costumava saída de Amaya como um guia.
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Stack;
import java.util.logging.Logger;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;
public class HTML2Text extends HTMLEditorKit.ParserCallback {
private static final Logger log = Logger
.getLogger(Logger.GLOBAL_LOGGER_NAME);
private StringBuffer stringBuffer;
private Stack<IndexType> indentStack;
public static class IndexType {
public String type;
public int counter; // used for ordered lists
public IndexType(String type) {
this.type = type;
counter = 0;
}
}
public HTML2Text() {
stringBuffer = new StringBuffer();
indentStack = new Stack<IndexType>();
}
public static String convert(String html) {
HTML2Text parser = new HTML2Text();
Reader in = new StringReader(html);
try {
// the HTML to convert
parser.parse(in);
} catch (Exception e) {
log.severe(e.getMessage());
} finally {
try {
in.close();
} catch (IOException ioe) {
// this should never happen
}
}
return parser.getText();
}
public void parse(Reader in) throws IOException {
ParserDelegator delegator = new ParserDelegator();
// the third parameter is TRUE to ignore charset directive
delegator.parse(in, this, Boolean.TRUE);
}
public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
log.info("StartTag:" + t.toString());
if (t.toString().equals("p")) {
if (stringBuffer.length() > 0
&& !stringBuffer.substring(stringBuffer.length() - 1)
.equals("\n")) {
newLine();
}
newLine();
} else if (t.toString().equals("ol")) {
indentStack.push(new IndexType("ol"));
newLine();
} else if (t.toString().equals("ul")) {
indentStack.push(new IndexType("ul"));
newLine();
} else if (t.toString().equals("li")) {
IndexType parent = indentStack.peek();
if (parent.type.equals("ol")) {
String numberString = "" + (++parent.counter) + ".";
stringBuffer.append(numberString);
for (int i = 0; i < (4 - numberString.length()); i++) {
stringBuffer.append(" ");
}
} else {
stringBuffer.append("* ");
}
indentStack.push(new IndexType("li"));
} else if (t.toString().equals("dl")) {
newLine();
} else if (t.toString().equals("dt")) {
newLine();
} else if (t.toString().equals("dd")) {
indentStack.push(new IndexType("dd"));
newLine();
}
}
private void newLine() {
stringBuffer.append("\n");
for (int i = 0; i < indentStack.size(); i++) {
stringBuffer.append(" ");
}
}
public void handleEndTag(HTML.Tag t, int pos) {
log.info("EndTag:" + t.toString());
if (t.toString().equals("p")) {
newLine();
} else if (t.toString().equals("ol")) {
indentStack.pop();
;
newLine();
} else if (t.toString().equals("ul")) {
indentStack.pop();
;
newLine();
} else if (t.toString().equals("li")) {
indentStack.pop();
;
newLine();
} else if (t.toString().equals("dd")) {
indentStack.pop();
;
}
}
public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
log.info("SimpleTag:" + t.toString());
if (t.toString().equals("br")) {
newLine();
}
}
public void handleText(char[] text, int pos) {
log.info("Text:" + new String(text));
stringBuffer.append(text);
}
public String getText() {
return stringBuffer.toString();
}
public static void main(String args[]) {
String html = "<html><body><p>paragraph at start</p>hello<br />What is happening?<p>this is a<br />mutiline paragraph</p><ol> <li>This</li> <li>is</li> <li>an</li> <li>ordered</li> <li>list <p>with</p> <ul> <li>another</li> <li>list <dl> <dt>This</dt> <dt>is</dt> <dd>sdasd</dd> <dd>sdasda</dd> <dd>asda <p>aasdas</p> </dd> <dd>sdada</dd> <dt>fsdfsdfsd</dt> </dl> <dl> <dt>vbcvcvbcvb</dt> <dt>cvbcvbc</dt> <dd>vbcbcvbcvb</dd> <dt>cvbcv</dt> <dt></dt> </dl> <dl> <dt></dt> </dl></li> <li>cool</li> </ul> <p>stuff</p> </li> <li>cool</li></ol><p></p></body></html>";
System.out.println(convert(html));
}
}
Como alternativa, pode-se usar HtmlCleaner :
private CharSequence removeHtmlFrom(String html) {
return new HtmlCleaner().clean(html).getText();
}
Use Html.fromHtml
HTML Tags são
<a href=”…”> <b>, <big>, <blockquote>, <br>, <cite>, <dfn>
<div align=”…”>, <em>, <font size=”…” color=”…” face=”…”>
<h1>, <h2>, <h3>, <h4>, <h5>, <h6>
<i>, <p>, <small>
<strike>, <strong>, <sub>, <sup>, <tt>, <u>
De acordo com do Android Documentações oficiais todas as tags na HTML irá exibir como um substituto genérico string que seu programa pode, então, passar e substituir com o Real cordas .
Html.formHtml
método leva um Html.TagHandler
e um Html.ImageGetter como argumentos, bem como o texto para análise.
Exemplo
String Str_Html=" <p>This is about me text that the user can put into their profile</p> ";
Em seguida
Your_TextView_Obj.setText(Html.fromHtml(Str_Html).toString());
saída
Esta é sobre mim texto que o usuário pode colocar em seu perfil
Mais uma forma pode ser a utilização de classe com.google.gdata.util.common.html.HtmlToText como
MyWriter.toConsole(HtmlToText.htmlToPlainText(htmlResponse));
Este não é o código de prova de bala embora e quando eu executá-lo em wikipedia entradas estou recebendo informação de estilo também. No entanto, eu acredito que para pequenos trabalhos / simples, isto seria eficaz.
Parece que você quer ir de HTML para texto simples.
Se for esse o olhar caso em www.htmlparser.org. Aqui está um exemplo que retira todas as tags a partir do arquivo html encontrado em uma URL.
Ele faz uso de org.htmlparser.beans.StringBean .
static public String getUrlContentsAsText(String url) {
String content = "";
StringBean stringBean = new StringBean();
stringBean.setURL(url);
content = stringBean.getStrings();
return content;
}
Aqui está uma outra maneira de fazê-lo:
public static String removeHTML(String input) {
int i = 0;
String[] str = input.split("");
String s = "";
boolean inTag = false;
for (i = input.indexOf("<"); i < input.indexOf(">"); i++) {
inTag = true;
}
if (!inTag) {
for (i = 0; i < str.length; i++) {
s = s + str[i];
}
}
return s;
}
Aqui está mais uma variante de como substituir tudo (tags HTML | Entidades HTML | espaço vazio em conteúdo HTML)
content.replaceAll("(<.*?>)|(&.*?;)|([ ]{2,})", "");
onde o conteúdo é uma String.
Pode-se também usar Apache Tika para esta finalidade. Por padrão, ele preserva espaços em branco do html despojado, que pode ser desejado em determinadas situações:
InputStream htmlInputStream = ..
HtmlParser htmlParser = new HtmlParser();
HtmlContentHandler htmlContentHandler = new HtmlContentHandler();
htmlParser.parse(htmlInputStream, htmlContentHandler, new Metadata())
System.out.println(htmlContentHandler.getBodyText().trim())
Uma maneira de reter informações de nova linha com JSoup deve preceder todas as novas tags de linha com alguma corda manequim, executar JSoup e substituir manequim string com "\ n".
String html = "<p>Line one</p><p>Line two</p>Line three<br/>etc.";
String NEW_LINE_MARK = "NEWLINESTART1234567890NEWLINEEND";
for (String tag: new String[]{"</p>","<br/>","</h1>","</h2>","</h3>","</h4>","</h5>","</h6>","</li>"}) {
html = html.replace(tag, NEW_LINE_MARK+tag);
}
String text = Jsoup.parse(html).text();
text = text.replace(NEW_LINE_MARK + " ", "\n\n");
text = text.replace(NEW_LINE_MARK, "\n\n");
Você pode simplesmente usar filtro HTML padrão do Android
public String htmlToStringFilter(String textToFilter){
return Html.fromHtml(textToFilter).toString();
}
O método acima irá retornar a string filtrada HTML para a sua entrada.
As minhas 5 centavos:
String[] temp = yourString.split("&");
String tmp = "";
if (temp.length > 1) {
for (int i = 0; i < temp.length; i++) {
tmp += temp[i] + "&";
}
yourString = tmp.substring(0, tmp.length() - 1);
}
Para obter formateed texto HTML puro você pode fazer isso:
String BR_ESCAPED = "<br/>";
Element el=Jsoup.parse(html).select("body");
el.select("br").append(BR_ESCAPED);
el.select("p").append(BR_ESCAPED+BR_ESCAPED);
el.select("h1").append(BR_ESCAPED+BR_ESCAPED);
el.select("h2").append(BR_ESCAPED+BR_ESCAPED);
el.select("h3").append(BR_ESCAPED+BR_ESCAPED);
el.select("h4").append(BR_ESCAPED+BR_ESCAPED);
el.select("h5").append(BR_ESCAPED+BR_ESCAPED);
String nodeValue=el.text();
nodeValue=nodeValue.replaceAll(BR_ESCAPED, "<br/>");
nodeValue=nodeValue.replaceAll("(\\s*<br[^>]*>){3,}", "<br/><br/>");
Para obter formateed texto simples mudança
por \ n e alterar última linha por:
nodeValue=nodeValue.replaceAll("(\\s*\n){3,}", "<br/><br/>");
classeString.replaceAll("\\<(/?[^\\>]+)\\>", "\\ ").replaceAll("\\s+", " ").trim()
Você pode simplesmente fazer um método com replaceAll múltipla () como
String RemoveTag(String html){
html = html.replaceAll("\\<.*?>","")
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
----------
----------
return html;
}
Use este link para a maioria das substituições comuns que você precisa: http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html
É simples, mas eficaz. Eu uso este método primeiro para remover o lixo, mas não a primeira linha ie replaceAll ( "\ <. *?>", ""), E mais tarde eu uso palavras-chave específicas de pesquisa para índices e, em seguida, usar .substring (início, fim ) método para despir material desnecessário. Como este é mais robusto e você pode fixar o ponto exatamente o que você precisa em toda a página html.
Remove HTML de corda. Em algum lugar temos de analisar uma string que é recebido por algumas respostas como HTTPResponse do servidor.
Então, precisamos analisá-lo.
Aqui vou mostrar como remover tags HTML de string.
// sample text with tags
string str = "<html><head>sdfkashf sdf</head><body>sdfasdf</body></html>";
// regex which match tags
System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("<[^>]*>");
// replace all matches with empty strin
str = rx.Replace(str, "");
//now str contains string without html tags