大家好
我有一个我想要的java字符串
1-从中删除除新行标记<br>
和</br>
之外的所有html标记,并在文本中保留文本内的标记。
2-解析后,文本结果相互连接,如:text1andtext2,文本之间没有空格分隔,我也想这样做。
这就是我在做的事情:
String html = "<div dir=\"ltr\">hello my friend<span>ECHO</span><br>how are you ?<br><br><div class=\"gmail_quote\">On Mon, Feb 14, 2011 at 10:45 AM, My Friend <span dir=\"ltr\"><<a href=\"mailto:notifications@mydomain.com\">notifications@mydomain.com</a>></span> wrote:<br> "
+ "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\"> ";
String parsedText = html.replaceAll("\\<.*?\\>", "");
System.out.println(parsedText);
当前输出:
hello my friendECHOhow are you ?On Mon, Feb 14, 2011 at 10:45 AM, My Friend <notifications@mydomain.com> wrote:
期望的输出:
hello my friend ECHO <br> how are you ? <br> <br> On Mon, Feb 14, 2011 at 10:45 AM, My Friend &`lt;notifications@mydomain.com> wrote:`
答案 0 :(得分:4)
你可以这样做:
final String html =
"<div dir=\"ltr\">hello my friend<span>ECHO</span><br>how are you ?" +
"<br><br><div class=\"gmail_quote\">On Mon, Feb 14, 2011 at 10:45 AM," +
" My Friend <span dir=\"ltr\"><<a href=\"mailto:notifications@mydo" +
"main.com\">notifications@mydomain.com</a>></span> wrote:<br><bloc" +
"kquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 0pt 0.8ex; bord" +
"er-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\"> ";
final Pattern tagPattern = Pattern.compile("<([^\\s>/]+).*?>");
final Matcher matcher = tagPattern.matcher(html);
final StringBuffer sb = new StringBuffer(html.length());
while(matcher.find()){
matcher
.appendReplacement(sb, matcher.group(1).equalsIgnoreCase("br")
? matcher.group()
: " ");
}
matcher.appendTail(sb);
final String parsedText = sb.toString();
System.out.println(parsedText);
<强>输出:强>
hello my friendECHO<br>how are you ?<br><br>On Mon, Feb 14, 2011 at 10:45 AM,
My Friend <notifications@mydomain.com> wrote:<br>
但我希望你知道Cthulhu is calling if you do。不要使用Regex解析HTML / XML !!
答案 1 :(得分:2)
我会
答案 2 :(得分:0)