C# Regex for only numbers from string

I have string with letters and numbers and I want have only numbers. For example:

string str = "4.2 43 f-2.1-1k 4. a.1 5asd11 54 -1.99";
Regex regex = new Regex("?????");            
Match m;
m = regex.Match(str);

while (m.Success)
{
    try
    {
        buffor[index] = float.Parse(m.ToString());
        index++;                      
    }
    catch (FormatException ex) { }
    m = m.NextMatch();             
}

In buffer array I want to have 4.2 43 4 54 -1.99. When regex = [ ][+-]?([0-9]*[.])?[0-9]+[ ] I have in buffer only 43 and 54.

2 answers

  • answered 2018-01-14 10:37 Andrei Odegov

    I modified slightly your snippet using the next regex (?<=^| )([-+]?\d+\.?(?:\d+)?)(?= |$).

    //Rextester.Program.Main is the entry point for your code. Don't change it.
    //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
    
    using System;
    using System.Text.RegularExpressions;
    using System.Globalization;
    
    namespace Rextester
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                string str = "4.2 43 f-2.1-1k 4. a.1 5asd11 54 -1.99";
                Regex regex = new Regex(@"(?<=^| )([-+]?\d+\.?(?:\d+)?)(?= |$)");            
                Match m;
                m = regex.Match(str);
    
                while (m.Success)
                {
                     try
                    {
                        //buffor[index] = float.Parse(m.ToString());
                        //index++;
                        Console.WriteLine(float.Parse(m.ToString(), CultureInfo.InvariantCulture));
                    }
                    catch (FormatException ex) { }
                    m = m.NextMatch();             
                }
            }
        }
    }
    

    But i have the question about how will you process numbers in the exponential notation.

  • answered 2018-01-14 10:37 shA.t

    I used below code for that:

    var str = "4.2 43 f-2.1-1k 4. a.1 5asd11 54 -1.99";
    var result =
        Regex.Matches(str, @"(?<=^|\s)(?<num>[\-+]?[0-9\.]*[0-9]+)([\s\.]|$)")
            .OfType<Match>()
            .Select(c => float.Parse(c.Groups["num"].ToString(), CultureInfo.InvariantCulture));
    

    Explanation:

    (?<=                 //-> check before match if
        ^|\s             //-> it's start of string -'^'- or a space character -'\s'-
    )                    
    (?<num>              // match with grouping and naming by 'num'
        -?               // an optional -'?'- dash
        [0-9\.]*         // optional dot or digits
        [0-9]+           // some digits
    )
    (                    //-> then check for
        [\s\.]|$         //-> dot -'\.'- or a space character or end of string -'$'-
    )