C#Regex仅用于字符串中的数字

时间:2018-01-14 10:37:23

标签: c# regex

我有字母和数字的字符串,我想只有数字。 例如:

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();             
}

在缓冲区数组中,我想拥有4.2 43 4 54 -1.99。当regex = [ ][+-]?([0-9]*[.])?[0-9]+[ ]我只在缓冲区4354

2 个答案:

答案 0 :(得分:1)

modified稍微使用下一个正则表达式(?<=^| )([-+]?\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();             
            }
        }
    }
}

但我有一个关于如何以指数表示法处理数字的问题。

答案 1 :(得分:0)

我使用下面的代码:

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));

说明:

(?<=                 //-> 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 -'$'-
)