92

I need to use Regex.Replace to remove all numbers and signs from a string.

Example input: 123- abcd33
Example output: abcd

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Gold
  • 60,526
  • 100
  • 215
  • 315

8 Answers8

161

Try the following:

var output = Regex.Replace(input, @"[\d-]", string.Empty);

The \d identifier simply matches any digit character.

Noldorin
  • 144,213
  • 56
  • 264
  • 302
26

You can do it with a LINQ like solution instead of a regular expression:

string input = "123- abcd33";
string chars = new String(input.Where(c => c != '-' && (c < '0' || c > '9')).ToArray());

A quick performance test shows that this is about five times faster than using a regular expression.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 1
    @SirDemon: Yes, LINQ is usually not the fastest option, but regular expressions have a bigger initial overhead. For operations on short strings setting up the RegEx object takes longer than the actual work. – Guffa Nov 01 '09 at 16:23
  • @Guffa Do you know how this scales? Lets say on 50k records should I go for RegEx? – Arnold Wiersma Feb 15 '16 at 13:53
  • 1
    @ArnoldWiersma: Either should scale pretty well, they are both basically linear, so there are no nasty surprises. I can't tell off hand which would be faster, you would have to test that. – Guffa Feb 15 '16 at 21:57
  • 6
    alternatively `new string(text.Where(char.IsLetter).ToArray());` – Skorunka František May 10 '18 at 11:18
  • @SkorunkaFrantišek, the problem here is that this also trims the string – Uke Feb 14 '21 at 15:40
11

Blow codes could help you...

Fetch Numbers:

return string.Concat(input.Where(char.IsNumber));

Fetch Letters:

return string.Concat(input.Where(char.IsLetter));
Ali Rasoulian
  • 419
  • 6
  • 12
5
var result = Regex.Replace("123- abcd33", @"[0-9\-]", string.Empty);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
3

As a string extension:

    public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Usage:

"My text 1232".RemoveIntegers(); // RETURNS "My text "
Sgedda
  • 1,323
  • 1
  • 18
  • 27
3

Different methods and which is the fastest if you have 100000 iterations to do.

Code:

        Stopwatch sw = new Stopwatch();
        var maxIterations = 100000;

        Console.WriteLine(@"Removing digits from string: ""1mir1112211a3bc9"" with Total {0}x iterations ",maxIterations);
        Console.WriteLine("\nReplace Operations");
        sw.Start();
        var str = "1mir1112211a3bc9";
        for (int i = 1; i <= maxIterations; i++)
        {
            str = "1mir1112211a3bc9";

            str = str.Replace("1", "")
                     .Replace("2", "")
                     .Replace("3", "")
                     .Replace("4", "")
                     .Replace("5", "")
                     .Replace("6", "")
                     .Replace("7", "")
                     .Replace("8", "")
                     .Replace("9", "")
                     .Replace("0", "");
        }
        sw.Stop();
        
        Console.WriteLine("Finalstring: " + str);
        Console.WriteLine("Elapsed time: " + sw.Elapsed.TotalMilliseconds + " Milliseconds");

        sw.Reset();

        //list for and if 
        Console.WriteLine("\nList Operations:");
        sw.Start();
        var str2 = "1mir1112211a3bc9";
        var listOfchars = new List<char>();
        for (int i = 1; i <= maxIterations; i++)
        {
             str2 = "1mir1112211a3bc9";
            for (int j = 0; j < str2.Length; j++)
            {
                if( !(char.IsDigit(str2[j])))
                    listOfchars.Add(str2[j]);
            }
            str2 = new string(listOfchars.ToArray());
            listOfchars.Clear();
        }
        sw.Stop();
        Console.WriteLine("Finalstring: " + str2);
        Console.WriteLine("Elapsed time: " + sw.Elapsed.TotalMilliseconds + " Milliseconds");

           sw.Reset();
        //LINQ
        Console.WriteLine("\nLINQ Operations");

        sw.Start();
            var str1 = "1mir1112211a3bc9";
        for (int i = 1; i <= maxIterations; i++)
        {
            str1 = "1mir1112211a3bc9";
            str1 = String.Concat(str1.Where(c => c != '-' && (c < '0' || c > '9')) );
        }
        sw.Stop();

        Console.WriteLine("Finalstring: " + str1);
        Console.WriteLine("Elapsed time: " + sw.Elapsed.TotalMilliseconds + " Milliseconds");

        //Regex
        sw.Reset();
        
        Console.WriteLine("\nRegex Operations");

        sw.Start();
        var str3 = "1mir1112211a3bc9";
        for (int i = 1; i <= maxIterations; i++)
        {
            str3 = "1mir1112211a3bc9";
            str3 = Regex.Replace(str3, @"[\d-]", string.Empty);
        }
        sw.Stop();

        Console.WriteLine("Finalstring: " + str3);
        Console.WriteLine("Elapsed time: " + sw.Elapsed.TotalMilliseconds + " Milliseconds");

Here are the Results:

Removing digits from string: "1mir1112211a3bc9" with Total 100000x iterations

Replace Operations
Finalstring: mirabc
Elapsed time: 37,8307 Milliseconds

List Operations:
Finalstring: mirabc
Elapsed time: 16,7803 Milliseconds

LINQ Operations
Finalstring: mirabc
Elapsed time: 34,5803 Milliseconds

Regex Operations
Finalstring: mirabc
Elapsed time: 252,1907 Milliseconds

amehmood
  • 51
  • 3
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 09 '22 at 03:22
2

the best design is:

public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }
2
text= re.sub('[0-9\n]',' ',text)

install regex in python which is re then do the following code.

Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40