venerdì 14 ottobre 2011

How To: Match and Remove Regex

Questa è una cosa che prima o poi mi deciderò di implementare in una classe che eredita string.. perchè giuro torna davvero comoda..


class Program
{
static void Main(string[] args)
{

string x = "DEL_Demo_Test__DEL";

Console.WriteLine(Trim(x, "_DEL"));

Console.ReadLine();
}

private static string Trim(string text, string find)
{
Regex r = new Regex(find+"$");
bool t = r.IsMatch(text);

if (t){ return Regex.Replace(text,find + "$",""); }

return text;
}
}



In questo ( anche se pur breve ) brano di codice è presentato un sistema decisamente comodo per "eliminare un gruppo di caratteri" che terminano una stringa.

L'utilizzo di RegularExpression a volte "salva" da spiacevoli inconvenienti.

Nessun commento: