[ Regex ] Remover tags HTML da string

- sexta-feira, 16 de julho de 2010

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.
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.



Blogado por Rafa Almeida as 18:05

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!
Rafael Almeida Rafael da Silva Almeida, 22 Desenvolvedor;
C#, VB.NET, Java, C, Phyton, Linq, MVC;
VSTS, SQL, TV Digital, Xletview;
eusou@rafaelalmeida.net
SKYPE: stupied4ever
MSN: r.almeidasilva@terra.com.br
Twitter

Ultimos Posts

Amigos