Saturday, March 24, 2012

Stripping out unwanted characters

How can I strip out unwanted characters in a string before updating the
database? For instance, in names & addresses in our client table, we want
only letters and numbers, no punctuation. Is there a way to do this?HI,

Use regular expression to remove unwanted characters and then send the
string to database. Here is a sample code to remove non-alphanumerical
characters from a string.

hoep this will help you...

public static void Main()

{

/*Reg expression to find non-alphanumeric characters*/

string pattern = @."[^A-Za-z0-9]";

/*include System.Text.RegularExpressions name space*/

Regex rgx = new Regex(pattern);

string inputStr = "ab$!Cd&%$gf!";

/*Replace non-alphanumeric characters with space*/

string outputStr = rgx.Replace(inputStr, " ");

Console.WriteLine("Output string:"+ outputStr);

}

Cheers
Vinu

"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?
Function StripUnwantedChars(ByVal StringToStrip AsString) AsString
Dim stripped AsString
If StringToStrip <> "" Then
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)
Return stripped
Else
Return ""
EndIf
EndFunction

Note : insert all the characters you want to strip inside the quotes.

For example, instead of :
stripped = Regex.Replace(StringToStrip, "<(.|\n)+?>", String.Empty)

use :
stripped = Regex.Replace(StringToStrip, "<!#(.|\n)+?>", String.Empty)

Juan T. Llibre, asp.net MVP
aspnetfaq.com : http://www.aspnetfaq.com/
asp.net faq : http://asp.net.do/faq/
foros de asp.net, en espaol : http://asp.net.do/foros/
===================================
"et" <eagletender2001@.yahoo.com> wrote in message news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the database? For instance,
> in names & addresses in our client table, we want only letters and numbers, no punctuation. Is
> there a way to do this?
Thanks, everyone, that's exactly what I was looking for.

"et" <eagletender2001@.yahoo.com> wrote in message
news:ODVkXK7NGHA.668@.TK2MSFTNGP11.phx.gbl...
> How can I strip out unwanted characters in a string before updating the
> database? For instance, in names & addresses in our client table, we want
> only letters and numbers, no punctuation. Is there a way to do this?

0 comments:

Post a Comment