質問
Java文字列からHTMLを削除する良い方法はありますか?
のような単純な正規表現 replaceAll("\\<.*?>","")
は機能しますが、&
などは正しく変換されず、2つの山括弧の間の非HTMLは削除されます(つまり、正規表現の.*?
は消えます)。
他のヒント
Android 向けに書いている場合は、これを行うことができます...
android.text.Html.fromHtml(instruction).toString()
ユーザーが<b>hey!</b>
を入力した場合、hey!
または<bhey!</b>
を表示しますか?最初の場合は、小なり記号をエスケープし、アンパサンド(およびオプションで引用符)をhtmlエンコードすれば問題ありません。 2番目のオプションを実装するためのコードの変更は次のとおりです。
replaceAll("\\<[^>]*>","")
ただし、ユーザーが<=>などの不正な形式を入力すると問題が発生します。
<!> quot; dirty <!> quot;を解析する JTidy もチェックアウトできます。 HTML入力。タグを削除してテキストを保持する方法を提供する必要があります。
htmlを削除しようとすると、ブラウザーには非常に寛容なパーサーがあり、見つけることができるライブラリよりも寛容なので、すべてのタグを削除するために最善を尽くしても(上記のreplaceメソッド、DOMライブラリ、またはJTidy)、出力を安全に保つために、残りのHTML特殊文字を必ずエンコードする必要があります 。
別の方法は、 javax.swing.text.html.HTMLEditorKit を使用してテキストを抽出することです。
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();
}
}
}
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("");
}
Jericho を使用しても非常に簡単で、一部のフォーマット(行ブレークやリンクなど)。
Source htmlSource = new Source(htmlText);
Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());
Renderer htmlRend = new Renderer(htmlSeg);
System.out.println(htmlRend.toString());
Androidでは、これを試してください:
String result = Html.fromHtml(html).toString();
HTMLエスケープは本当に難しいのです。ライブラリコードを使用してこれを行うことを絶対にお勧めします。 Apacheの StringEscapeUtilsをご覧ください。 これをJavaで処理するための非常に優れたライブラリです。
単純にJsoup.parse(html).text()
を行うことで受け入れられる答えには、2つの潜在的な問題があります(JSup 1.7.3を使用):
- テキストから改行を削除します
- テキスト
<script>
を<script>
に変換します
これを使用してXSSから保護する場合、これは少し面倒です。 JSoupと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);
最後のステップは、出力をプレーンテキストとして使用する必要があるためです。 HTML出力のみが必要な場合は、削除できるはずです。
そして、ここにたくさんのテストケースがあります(入力から出力へ):
{"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"}
改善する方法を見つけたら、お知らせください。
HTMLを削除する前に<br/>
および</p>
タグを改行で置き換えて、Timが示唆するように判読できない混乱にならないようにします。
HTMLタグを削除することを考えることができる唯一の方法は、山括弧の間に非HTMLを残すことは、 HTMLタグのリスト。これらの線に沿って何か...
replaceAll("\\<[\s]*tag[^>]*>","")
次に、&
などのHTMLデコード特殊文字。結果はサニタイズされると見なされるべきではありません。
これは機能するはずです-
これを使用
text.replaceAll('<.*?>' , " ") -> This will replace all the html tags with a space.
そしてこれ
text.replaceAll('&.*?;' , "")-> this will replace all the tags which starts with "&" and ends with ";" like , &, > etc.
受け入れられた答えは、私が示したテストケースでは機能しませんでした。<!> quot; a <!> lt; bまたはb <!> gt; c <!> quot; <!> quot; a bまたはb <!> gt; c <!> quot;。
したがって、代わりにTagSoupを使用しました。これが私のテストケース(および他のいくつか)で機能したショットです。
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 {
}
}
これは古いことはわかっていますが、HTMLのフィルタリングが必要なプロジェクトに取り組んでいましたが、これはうまくいきました。
noHTMLString.replaceAll("\\&.*?\\;", "");
これの代わりに:
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
ここでは、ブレークとリストの書式設定を処理するための、少し具体的な更新を示します。 Amayaの出力をガイドとして使用しました。
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));
}
}
または、 HtmlCleaner を使用できます:
private CharSequence removeHtmlFrom(String html) {
return new HtmlCleaner().clean(html).getText();
}
Html.fromHtml
HTML タグは
<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>
Android <!>#8217;公式ドキュメント HTML 内のタグは、一般的な置換 String として表示され、プログラムはそれを通過して実際の strings 。
Html.formHtml
メソッドは、引数として Html.TagHandler
とHtml.ImageGetterを取り、解析するテキストを受け取ります。
例
String Str_Html=" <p>This is about me text that the user can put into their profile</p> ";
その後
Your_TextView_Obj.setText(Html.fromHtml(Str_Html).toString());
出力
これは、ユーザーが自分のプロファイルに入れることができる私のテキストです
もう1つの方法は、com.google.gdata.util.common.html.HtmlToTextクラスを使用することです。
MyWriter.toConsole(HtmlToText.htmlToPlainText(htmlResponse));
これは防弾コードではありません。ウィキペディアのエントリで実行すると、スタイル情報も取得されます。ただし、小規模/単純なジョブの場合、これは効果的だと思います。
HTMLからプレーンテキストに移行したいようです。
その場合は、www.htmlparser.orgをご覧ください。 URLにあるhtmlファイルからすべてのタグを削除する例を次に示します。
org.htmlparser.beans.StringBean を使用します。
static public String getUrlContentsAsText(String url) {
String content = "";
StringBean stringBean = new StringBean();
stringBean.setURL(url);
content = stringBean.getStrings();
return content;
}
別の方法があります:
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;
}
すべてを置き換える方法のもう1つのバリエーションがあります(HTMLタグ| HTMLエンティティ| HTMLコンテンツの空のスペース)
content.replaceAll("(<.*?>)|(&.*?;)|([ ]{2,})", "");
ここで、コンテンツは文字列です。
この目的で Apache Tika を使用することもできます。デフォルトでは、削除されたhtmlから空白を保持しますが、これは特定の状況で望ましい場合があります:
InputStream htmlInputStream = ..
HtmlParser htmlParser = new HtmlParser();
HtmlContentHandler htmlContentHandler = new HtmlContentHandler();
htmlParser.parse(htmlInputStream, htmlContentHandler, new Metadata())
System.out.println(htmlContentHandler.getBodyText().trim())
JSoupで改行情報を保持する1つの方法は、すべての改行タグの前にダミー文字列を置き、JSoupを実行し、ダミー文字列を<!> quot; \ n <!> quot;に置き換えます。
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");
AndroidのデフォルトHTMLフィルターを使用できます
public String htmlToStringFilter(String textToFilter){
return Html.fromHtml(textToFilter).toString();
}
上記のメソッドは、入力に対してHTMLフィルタリングされた文字列を返します。
私の5セント:
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);
}
フォーマットされたプレーンhtmlテキストを取得するには、次のようにします。
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/>");
フォーマットされたプレーンテキストを取得するには、<!> lt; br / <!> gt;を変更します。 \ nで最後の行を次のように変更します:
nodeValue=nodeValue.replaceAll("(\\s*\n){3,}", "<br/><br/>");
classeString.replaceAll("\\<(/?[^\\>]+)\\>", "\\ ").replaceAll("\\s+", " ").trim()
次のような複数のreplaceAll()を使用してメソッドを作成できます
String RemoveTag(String html){
html = html.replaceAll("\\<.*?>","")
html = html.replaceAll(" ","");
html = html.replaceAll("&"."");
----------
----------
return html;
}
必要な最も一般的な代替品には、このリンクを使用します。 http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html
シンプルですが効果的です。最初にこのメソッドを使用してジャンクを削除しますが、最初の行ではなくreplaceAll(<!> quot; \ <!> lt;。*?<!> gt; <!> quot;、<!> quot; <! > quot;)、および後で特定のキーワードを使用してインデックスを検索し、.substring(start、end)メソッドを使用して不要なものを取り除きます。これはより堅牢であり、htmlページ全体で必要なものを正確に特定できるためです。
文字列からHTMLタグを削除します。サーバーからのHttpresponseのようないくつかの応答によって受信される文字列を解析する必要がある場所。
だから解析する必要があります。
文字列からhtmlタグを削除する方法を示します。
// 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