【发布时间】:2022-01-25 12:24:29
【问题描述】:
我使用这种方法将 html 转换为纯文本,但它在这个 html 标签中存在一些错误
方法:
public string HtmlToPlainText(string htmlText)
{
//const string tagWhiteSpace = @"(>|$)(\W|\n|\r)+<";//matches one or more (white space or line breaks) between '>' and '<'
const string stripFormatting = @"<[^>]*(>|$)";//match any character between '<' and '>', even when end tag is missing
const string lineBreak = @"<(br|BR)\s{0,1}\/{0,1}>";//matches: <br>,<br/>,<br />,<BR>,<BR/>,<BR />
var lineBreakRegex = new Regex(lineBreak, RegexOptions.Multiline);
var stripFormattingRegex = new Regex(stripFormatting, RegexOptions.Multiline);
//var tagWhiteSpaceRegex = new Regex(tagWhiteSpace, RegexOptions.Multiline);
var text = htmlText;
//Decode html specific characters
text = System.Net.WebUtility.HtmlDecode(text);
//Remove tag whitespace / line breaks
//text = tagWhiteSpaceRegex.Replace(text, "><");
//Replace < br /> with line breaks
text = lineBreakRegex.Replace(text, Environment.NewLine);
//Strip formatting
text = stripFormattingRegex.Replace(text, string.Empty);
return text;
}
这是我的 html 文本:
<h3> This is a simple title </h3> </br> <p>Lorem ipsum <b> dolor sit </b> amet consectetur, <i>adipisicing elit.</i> </p>这是我的结果:
这是一个简单的标题 Lorem ipsum dolor sit amet consectetur,
减肥精英。结果应该是:
这是一个简单的标题
Lorem ipsum dolor sit amet consectetur, adipisicing elit.
我认为错误来自条带格式。我该如何解决?
【问题讨论】:
-
您不应该使用正则表达式从 html 中提取数据。
-
您的意思是
<br />而不是</br>? -
你为什么透露你的问题来自here的解决方案?
-
这能回答你的问题吗? How do you convert Html to plain text?