2

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!

12 Answers 12

15

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

Regex.Replace(input, @"\D+", "")
Sign up to request clarification or add additional context in comments.

4 Comments

Exactly what I was going to write. Make sure you store the return value. string str = Regex.Replace(input, "\D+", "");
that will replace both the "-" and the "d"? that's not as hard as I thought it would be.
the \D is an expression to look for any non-digit characters. They are then replaced by an empty char "".
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.
4

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());

5 Comments

+1 for being original, though I'd be interested in knowing how well this performs compared to the 8 billion regex solutions.
@Matthew: I made a quick test, and slightly surprising this is about three times faster than the Regex version.
Even shorter: code = new String(code.Where(Char.IsDigit).ToArray());
@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: I used the static method. I just copied the code from Lucero's answer.
2

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

RegEx.Replace("23232-2222-d23231", "\\D+", "");

1 Comment

Please use + or no quantifier. Using * will cause lots of 0-length matches.
2

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

Comments

1

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.

Comments

0

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.

1 Comment

This is too specialised for only that one example. Regex isn't really tougher and will catch all non digit values.
0

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, "");
}

Comments

0

I would use a regular expression.

See this post Regex for numbers only

Comments

0

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();
    }

Comments

0

Try

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

Comments

0

You could use LINQ:

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

Comments

-1

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.

4 Comments

And if I had string str = "foo/234335"? Oops.
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.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.