Search code examples
c#regexdigits

How can I return only the digits from a large string with symbols, letters and of course digits with C#


I have this code down here and I need to return the args.Content (my input data) with only digits and deleteing the rest of characteres. I've been trying many things with regular expressions but it didnt work for me. I have almost no idea of C# and I really need the help from the programers of this website.

using System;
using VisualWebRipper.Internal.SimpleHtmlParser;
using VisualWebRipper;
public class Script
{

    public static string TransformContent(WrContentTransformationArguments args)
    {
        try
        {
            //Place your transformation code here.
            //This example just returns the input data
            return args.Content;
        }
        catch(Exception exp)
        {
            //Place error handling here
            args.WriteDebug("Custom script error: " + exp.Message);
            return "Custom script error";
        }
    }
}

Hope you can help


Solution

  • Just delete anything that is not a digit. There is a predefined character class for digits: \d, the negation is \D.

    So you regex is simply:

    \D+
    

    In your C# code it would be something like

    return Regex.Replace(args.Content, @"\D+", "");