September 05, 2007

Removing Non-Numeric Characters from a string (The easy way)

I was searching the web for a way to easily remove all non numeric characters from a string, but the only thing I found was some "for loop" examples, which really slowed down my application, so after a little research I came up with a simple way to do it using Regular Expressions

Here it goes:

string Temp = "Hax00r L33t";
string Output = Regex.Replace(Temp, "[^0-9]", "");


Back to Home

7 comments:

Anonymous said...

Sheer genius!
Sometimes the obvious ISN'T.

Many thanks for this, you've saved me hours of silliness.

Anonymous said...

Good stuff, thanks.

Anonymous said...

thanks, that's gooode

Anonymous said...

Terribly elegant!

Isaac said...

Doesn't work very well if you have a decimal point though does it? Needs a bit more work.

Isaac said...

Apologies:

Regex.Replace(Temp, "[^.0-9]", "") works. I was confused for a momemt thinking that the . stood for the wildcard (any) character and that I had to escape it.

Anonymous said...

Decimal point is a non-numeric character, now isn't it?

Post a Comment