#c# #model-view-controller
#c# #модель-представление-контроллер
Вопрос:
Как удалить этот текст
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<test@test.com>
</body>
</html>
чтобы выглядеть как
My First Heading
My first paragraph.
<test@test.com>
Используя функцию
public static string StripHTML(this string htmlText)
{
var reg = new Regex("<(.|n)*?>", RegexOptions.IgnoreCase);
return reg.Replace(htmlText, "");
}
Я получаю
Мой первый заголовок — мой первый абзац.
Комментарии:
1. <test@test.com >: он не будет отображаться на HTML-странице. вы должны htmlencode этот текст msdn.microsoft.com/en-us/library/w3te6wfz.aspx или вам нужно создать очень специфическое регулярное выражение, чтобы обходить электронные письма в знаках <>.
Ответ №1:
Используйте Html Agility Pack для таких операций. Это быстрее, чем любое регулярное выражение, и поддерживает LINQ.
Ответ №2:
static void Main(string[] args)
{
string modified_html = emas(input);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(modified_html);
string test1 = doc.DocumentNode.InnerText;
Console.WriteLine();
var reg = new Regex("<(.|n)*?>", RegexOptions.IgnoreCase);
Console.WriteLine(reg.Replace(modified_html , ""));
Console.Read();
}
public static string emas(string text)
{
string stripped = text;
const string MatchEmailPattern =
@"(([w-] .) [w-] |([a-zA-Z]{1}|[w-]{2,}))@"
@"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9]).([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])."
@"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9]).([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
@"([a-zA-Z] [w-] .) [a-zA-Z]{2,4})";
Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
int noOfMatches = matches.Count;
// Report on each match.
foreach (Match match in matches)
{
stripped = stripped.Replace("<" match.Value ">" , match.Value);
}
return stripped;
}
static string input = " Your html goes here ";
Комментарии:
1. Может быть, у меня будет <h1> Мой первый заголовок</h1> <p><test@test.com > Мой первый абзац. </p> Только я хочу, чтобы функция html strip не удаляла адрес электронной почты.
2. Я модифицировал код. Вы не можете использовать html agility pack, потому что он удаляет весь текст, содержащийся в <> . Это то, во что я верю. Теперь я ищу адрес электронной почты и удаляю системные символы < и > рядом с электронной почтой . Пожалуйста, сообщите, есть ли у вас какие-либо проблемы