Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number extraction from strings using Regex

i have this C# code that i found and then improved upon for my needs, but now i would like to make it work for all numeric data types.

    public static int[] intRemover (string input)
    {
        string[] inputArray = Regex.Split (input, @"\D+");
        int n = 0;
        foreach (string inputN in inputArray) {
            if (!string.IsNullOrEmpty (inputN)) {
                n++;
            }
        }
        int[] intarray = new int[n];
        n = 0;
        foreach (string inputN in inputArray) {
            if (!string.IsNullOrEmpty (inputN)) {
                intarray [n] = int.Parse (inputN);
                n++;
            }
        }
        return intarray;
    }

This works well for trying to extract whole number integers out of strings but the issue that i have is that the regex expression i am using is not setup to account for numbers that are negative or numbers that contain a decimal point in them. My goal in the end like i said is to make a method out of this that works upon all numeric data types. Can anyone help me out please?

like image 551
Alex Zywicki Avatar asked Nov 30 '25 20:11

Alex Zywicki


1 Answers

You can match it instead of splitting it

public static decimal[] intRemover (string input)
{
    return Regex.Matches(input,@"[+-]?\d+(\.\d+)?")//this returns all the matches in input
                .Cast<Match>()//this casts from MatchCollection to IEnumerable<Match>
                .Select(x=>decimal.Parse(x.Value))//this parses each of the matched string to decimal
                .ToArray();//this converts IEnumerable<decimal> to an Array of decimal
}

[+-]? matches + or - 0 or 1 time

\d+ matches 1 to many digits

(\.\d+)? matches a (decimal followed by 1 to many digits) 0 to 1 time


Simplified form of the above code

    public static decimal[] intRemover (string input)
    {
        int n=0;
        MatchCollection matches=Regex.Matches(input,@"[+-]?\d+(\.\d+)?");
        decimal[] decimalarray = new decimal[matches.Count];

        foreach (Match m in matches) 
        {
                decimalarray[n] = decimal.Parse (m.Value);
                n++;
        }
        return decimalarray;
    }
like image 93
Anirudha Avatar answered Dec 02 '25 09:12

Anirudha