[ Regex ] Remover tags HTML da string
- sexta-feira, 16 de julho de 2010Mais 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.
Fiz essa pergunta para alguns programadores iniciantes, e todos me responderam:
"-Faz um replace em nas tags HTML e remove todas elas".
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. vamus 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.
Vinícius
-6/8/2010 - 18:12
hahaha e eu achando que ia encontrar um site a la "gamesdobo.hpg" mas animal esse bloguinho hein ficou bem didático! saudades cara, abraço!
Ultimos Posts
25/7/2010
16/7/2010
8/7/2010
29/6/2010
8/2/2010
Amigos
Navarro
Klaus
Andre
Danilo
Tomás
Carolina Andrade
Design By Carolina Andrade
Rafael da Silva Almeida, 22 Desenvolvedor;
