Anyone have a regex expression to create a numeric-only string from a formatted string?

  • Thread starter Thread starter Ray Stevens
  • Start date Start date
R

Ray Stevens

I would like to quickly strip out all non-numeric characters from a string
(including whitespace) into a new string (i.e., remove the edit mask). Would
RegEx be the best way to do this and, if so, what is the syntax?
 
Ray,
Regex would probably work, but why not just use a simple loop?

String SomeString = "blah044954blah";
StringBuilder NewString = new StringBuilder();
for (int i = 0;i < SomeString.Length;i++)
{
if (!(((int) SomeString) >= 48 || ((int) SomeString) <= 57)) //
Assuming ASCII of course
{
NewString.Append(SomeString);
}
}
SomeString = NewString.ToString();

This isn't the cleanest code, but it is fast.

Take care.
 
Could be as simple as

Regex.Replace(" 12-34 ", @"\D", String.Empty)

If you don't need decimal or thousand separators, which you most like likely
do need... Then you're on your own :-)

HTH,
Alexander
 
Back
Top