Saturday, March 24, 2012

strip non-numeric characters

Is there simple way to take a string that should be all numeric (like a
credit card number) and strip out anything that isn't a digit? In the past
I've done this in VFP using the IsDigit() function, looping through each
character. It was a little awkward, but worked. Is there something similar,
or better for vb.net?

Thanks!

MattThe IsNumeric function should fill the bill...

Dim MyVar As Object
Dim MyCheck As Boolean
' ...
MyVar = "53" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "459.95" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns True.
' ...
MyVar = "45 Help" ' Assign value.
MyCheck = IsNumeric(MyVar) ' Returns False.

Regards,
January Smith

"MattB" <somedudeus@.yahoo.com> wrote in message
news:2hmemqFen4c9U1@.uni-berlin.de...
> Is there simple way to take a string that should be all numeric (like a
> credit card number) and strip out anything that isn't a digit? In the past
> I've done this in VFP using the IsDigit() function, looping through each
> character. It was a little awkward, but worked. Is there something
similar,
> or better for vb.net?
> Thanks!
> Matt
I would try Regex. You can look for \d and pull all instances, then concat
back the resulting array. There are a couple of other ways to work with
this.

Note that VB.NET still has IsNumber() or IsNumeric() [forget which one], so
you can still loop and test, if you want to go with VB.NET.

Another option is convert to a char array and test the numeric value of each
char. The ASCII value for numbers is extremely predictable.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

************************************************
Think Outside the Box!
************************************************
"MattB" <somedudeus@.yahoo.com> wrote in message
news:2hmemqFen4c9U1@.uni-berlin.de...
> Is there simple way to take a string that should be all numeric (like a
> credit card number) and strip out anything that isn't a digit? In the past
> I've done this in VFP using the IsDigit() function, looping through each
> character. It was a little awkward, but worked. Is there something
similar,
> or better for vb.net?
> Thanks!
> Matt
You can use the Regex.Replace method to check for any characters (\w) and replace them with an empty string. The result that would come out is a string that is all numeric.

0 comments:

Post a Comment