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!

SilentGhost
  • 264,945
  • 58
  • 291
  • 279
user181218
  • 1,535
  • 3
  • 26
  • 36

12 Answers12

15

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

Regex.Replace(input, @"\D+", "")
David Hall
  • 30,887
  • 10
  • 88
  • 121
Lucero
  • 56,592
  • 6
  • 112
  • 151
  • 2
    Exactly what I was going to write. Make sure you store the return value. string str = Regex.Replace(input, "\D+", ""); – Alastair Pitts Oct 13 '09 at 12:50
  • that will replace both the "-" and the "d"? that's not as hard as I thought it would be. – Ryan Alford Oct 13 '09 at 12:51
  • 1
    the \D is an expression to look for any non-digit characters. They are then replaced by an empty char "". – Alastair Pitts Oct 13 '09 at 12:52
  • 1
    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 Oct 13 '09 at 12:52
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());
Guffa
  • 640,220
  • 96
  • 678
  • 956
  • +1 for being original, though I'd be interested in knowing how well this performs compared to the 8 billion regex solutions. – Matthew Scharley Oct 13 '09 at 13:09
  • 1
    @Matthew: I made a quick test, and slightly surprising this is about three times _faster_ than the Regex version. – Guffa Oct 13 '09 at 14:00
  • Even shorter: code = new String(code.Where(Char.IsDigit).ToArray()); – cfern Oct 13 '09 at 15:08
  • @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 Oct 13 '09 at 23:21
  • @Matthew: I used the static method. I just copied the code from Lucero's answer. – Guffa Oct 14 '09 at 05:20
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.

David Hall
  • 30,887
  • 10
  • 88
  • 121
RC1140
  • 7,492
  • 14
  • 42
  • 67
2

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

RegEx.Replace("23232-2222-d23231", "\\D+", "");
Geoff
  • 4,440
  • 3
  • 24
  • 38
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.

dove
  • 19,761
  • 14
  • 82
  • 103
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.

Ryan Alford
  • 7,118
  • 5
  • 38
  • 54
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, "");
}
Matthew Scharley
  • 115,776
  • 51
  • 189
  • 215
0

I would use a regular expression.

See this post Regex for numbers only

Community
  • 1
  • 1
Anthony Shaw
  • 8,043
  • 4
  • 39
  • 61
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();
    }
bruno conde
  • 46,109
  • 14
  • 94
  • 114
0

Try

string str="23232-2222-d23231";
str=Regex.Replace(str, @"\D+", String.Empty);
Himadri
  • 7,624
  • 14
  • 45
  • 69
0

You could use LINQ:

string allDigits = new String(input.Where(c => Char.IsDigit(c)).ToArray());
Echilon
  • 9,631
  • 27
  • 126
  • 209
Lee
  • 133,981
  • 18
  • 209
  • 268
-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.

Binz
  • 580
  • 4
  • 9
  • And if I had `string str = "foo/234335"`? Oops. – Matthew Scharley Oct 13 '09 at 12:56
  • 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 Oct 13 '09 at 13:19
  • 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 Oct 13 '09 at 13:40
  • 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 Oct 13 '09 at 13:49