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

Sheer genius!
ReplyDeleteSometimes the obvious ISN'T.
Many thanks for this, you've saved me hours of silliness.
Good stuff, thanks.
ReplyDeletethanks, that's gooode
ReplyDeleteTerribly elegant!
ReplyDeleteDoesn't work very well if you have a decimal point though does it? Needs a bit more work.
ReplyDeleteApologies:
ReplyDeleteRegex.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.
Decimal point is a non-numeric character, now isn't it?
ReplyDeleteelegant, indeed. thanks!
ReplyDeleteVery nice - perfect solution
ReplyDeleteKudos to you and Kudos to Isaac that published the version for floating point numbers.
ReplyDeleteWhat about negative numbers?
ReplyDeleteHere is the full fledged version:
Regex.Replace(Temp, "[^-.0-9]", "")
Enjoy
G~
I implemented two extension methods for string to remove non-numeric chars. One with a loop and one using the RegEx.
ReplyDeleteThe extension method using the loop is faster.
Tnx great solution!
ReplyDeleteYou and google rock!!!
Nice!
ReplyDeleteThanks for sharing!
Sébastien D'Errico
sweet! Thanks.
ReplyDeleteMany thanks! you just saved me hours of messing about with something that should be obvious! :)
ReplyDeleteVery useful. Thanks!
ReplyDeleteSheer beauty!
ReplyDeleteoh! this is cool dude :)
ReplyDeletesimple'n useful
"the only thing I found was some 'for loop' examples, which really slowed down my application"
ReplyDeleteummmm, I think you'll find that regex also loops through your string and probably has much more overhead than a simple specifically written piece of code. It's selling point is ease of coding, not speed of execution.
the whole thing fails when the string as all characters and then a single number
ReplyDeleteHere is the Linq implementation, which, surprisingly, performs a bit faster than Regex:
ReplyDeletestring temp = "h4xx0r 133t";
string output = new string(temp.Where(ch => char.IsDigit(ch)).ToArray());
What function should we include to use regex.replace?
ReplyDeletegoogle
ReplyDeleteNice one added this as an extension method see below:
ReplyDeletepublic static class StringExtensionMethods
{
public static string RemoveNonNumericCharacters(this string suppliedString)
{
return Regex.Replace(suppliedString, "[^0-9]", "");
}
}