RegEx – Como Remover Tags HTML de uma string
Mais uma vez quero demonstrar como um regex, utilizado corretamente, pode ser poderoso. Imagine uma string qualquer onde você tenha tags HTML dentro:
“<p>Hi, <br/> “text .</strong>“</p> bad html </ul>will be removed too.”
Agora imagine que você tenha que remover todas as tags HTML dessa string.
Já vi muita gente fazer um replace nas tags HTML (uma por uma) e substituilas pela string vazia.
Realmente é uma saida, mas não é a mais inteligente, funciona até que alguem coloque uma tag que você não tenha previsto. Uma maneira mais eficiente de fazer isso, é usando um Regex. vamos ao exemplo:
static void Main(string[] args)
{
// Some String
const string text = "<p>Hi, <br/> “Walking on water and developing software from a specification are easy if both are <strong>frozen.</strong>“ - Edward V. Berard</p> here some bad html </ul>will be removed too.";
// Write the string with the html tags
Console.WriteLine(text);
// Write the string without the html tags
Console.WriteLine(RemoveHtmlTags(text));
Console.ReadLine();
}
private static string RemoveHtmlTags(string htmlString)
{
// Regex to find all the html tags
const string pattern = @"<(.|\n)*?>";
// Return the string without html tags
return Regex.Replace(htmlString, pattern, string.Empty);
}
Achei que podia ajudar algumas pessoas, então resolvi postar.
Creditos para http://aliraza.wordpress.com/, foi la que achei a primeira versão.