views:

242

answers:

12

Hi,

Say I have a string containing numbers and other chars.

I want to reduce the string to numbers only.

F.e. from 23232-2222-d23231 to 23232222223231

Can this be done with string.replace()?

if not, what's the simplest and shortest way?

10x!

+2  A: 

Yes you can use String.replace but it would be wiser to use regex so that you can match alot more criteria with alot less effort

RC1140
+15  A: 

There a a bunch of possibilities, from Regular Expressions to handling the text yourself. I'd go for this:

Regex.Replace(input, @"\D+", "")
Lucero
Exactly what I was going to write. Make sure you store the return value.string str = Regex.Replace(input, "\D+", "");
Alastair Pitts
that will replace both the "-" and the "d"? that's not as hard as I thought it would be.
Eclipsed4utoo
the \D is an expression to look for any non-digit characters. They are then replaced by an empty char "".
Alastair Pitts
Yes, because it replaces all series of non-digit characters (\d is digit, \D is non-digit) with an empty string, leaving you with only digit characters.
Lucero
A: 

The simplest would be to use Replace.

 string test = "23232-2222-d23231";
 string newString = test.Replace("-","").Replace("d","");

But using REGEX would be better, but tougher.

Eclipsed4utoo
This is too specialised for only that one example. Regex isn't really tougher and will catch all non digit values.
Alastair Pitts
+2  A: 

The best way would be to user Regular Expressions. You example would be:

RegEx.Replace("23232-2222-d23231", "\\D+", "");
Geoff
Please use `+` or no quantifier. Using `*` will cause lots of 0-length matches.
Matthew Scharley
You are too quick. Was just making that edit :-)
Geoff
A: 

It is not (easily) possible with string.Replace(). The simplest solution is the following function/code:

public string GetDigits(string input)
{
    Regex r = new Regex("[^0-9]+");
    return r.Replace(input, "");
}
Matthew Scharley
A: 

I would use a regular expression.

See this post http://stackoverflow.com/questions/273141/regex-for-numbers-only

Anthony Shaw
A: 

You can use a regular expression.

string str = "sdfsdf99393sdfsd";
str = Regex.Replace(str, @"[a-zA-Z _\-]", "");

I've used this to return only numbers in a string before.

Binz
And if I had `string str = "foo/234335"`? Oops.
Matthew Scharley
I was just trying to give an example of using regex. In the specific circumstance I took the code from the input was controlled so didn't have to escape for the circumstance you note. I didn't post the entire routine since trying to keep example code small. I figure anyone remotely familiar with regular expressions would realize they had to create an appropriate one for what they're trying to achieve. I suppose I should have added a note that the expression itself was not to be taken as a means for handling every circumstance one might encounter.
Binz
If the OP knew how to use regex's, I'm sure they could have surmissed that this would be an excellent case to use them for. By the way, thankyou for downvoting my working answer. It's nice to know someone cares.
Matthew Scharley
Your welcome. I just voted you back up. No need to do to you what I didn't appreciate, hasty reaction on my part. See I do care.
Binz
A: 

You can use a simple extension method:

    public static string OnlyDigits(this string s)
    {
        if (s == null)
            throw new ArgumentNullException("null string");

        StringBuilder sb = new StringBuilder(s.Length);
        foreach (var c in s)
        {
            if (char.IsDigit(c))
                sb.Append(c);
        }
        return sb.ToString();
    }
bruno conde
+1  A: 

Regular expressions, as sampled, are the simplest and shortest.

I wonder if below would be faster?

            string sample = "23232-2222-d23231";
            StringBuilder resultBuilder = new StringBuilder(sample.Length);
            char c;
            for (int i = 0; i < sample.Length; i++)
            {
                c = sample[i];
                if (c >= '0' && c <= '9')
                {
                    resultBuilder.Append(c);
                }
            }
            Console.WriteLine(resultBuilder.ToString());
            Console.ReadLine();

guessing it would depend on a few things, including string length.

dove
+4  A: 

Well, you will get about 874355876234857 answers with String.Replace and Regex.Replace, so here's a LINQ solution:

code = new String((from c in code where Char.IsDigit(c) select c).ToArray());

Or using extension methods:

code = new String(code.Where(c => Char.IsDigit(c)).ToArray());
Guffa
+1 for being original, though I'd be interested in knowing how well this performs compared to the 8 billion regex solutions.
Matthew Scharley
@Matthew: I made a quick test, and slightly surprising this is about three times _faster_ than the Regex version.
Guffa
Even shorter: code = new String(code.Where(Char.IsDigit).ToArray());
cfern
@Guffa: Not entirely surprised, but did your solution use the same `Regex` object, use the static `Replace` method, or did it recreate a couple dozen `Regex` objects? The first option would be fastest, though may not be representative of real world use.
Matthew Scharley
@Matthew: I used the static method. I just copied the code from Lucero's answer.
Guffa
A: 

Try

string str="23232-2222-d23231";
str=Regex.Replace(str, @"\D+", String.Empty);
Himadri
A: 

You could use linq:

string allDigits = new String(input.Where(c => Char.IsDigit(c)).ToArray());
Lee