在C#中使用RegEx验证浮点数

Joh*_*ith 10 c# regex validation wpf

我试图只TextBox在WPF中创建一个数字,我有这个代码:

void NumericTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    e.Handled = !IsValidInput(e.Text);
}

private bool IsValidInput(string p)
{
    switch (this.Type)
    {
        case NumericTextBoxType.Float:
            return Regex.Match(p, "^[0-9]*[.][0-9]*$").Success;
        case NumericTextBoxType.Integer:                    
        default:
            return Regex.Match(p, "^[0-9]*$").Success;                    
    }
}

// And also this!
public enum NumericTextBoxType
{
    Integer = 0, 
    Float = 1
}
Run Code Online (Sandbox Code Playgroud)

当我将类型设置为Integer时,它运行良好,但对于Float,它没有.

我可以使用那么多NumericTextBox控件,但我想知道为什么这个不起作用?

And*_*per 23

试试这个:

@"^[0-9]*(?:\.[0-9]*)?$"
Run Code Online (Sandbox Code Playgroud)

你需要逃避这段时期.并且使句点和小数部分可选是一个好主意.

如果需要处理负值,可以在每个模式中-?的第[0-9]一个之前添加.

更新

测试如下:

var regex = new Regex(@"^[0-9]*(?:\.[0-9]*)?$");
Console.WriteLine(new bool[] {regex.IsMatch("blah"),
                              regex.IsMatch("12"),
                              regex.IsMatch(".3"),
                              regex.IsMatch("12.3"),
                              regex.IsMatch("12.3.4")});
Run Code Online (Sandbox Code Playgroud)

结果是

False 
True 
True 
True 
False 
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nov 13

我建议您使用Double.TryParse()方法而不是正则表达式验证.使用TryParse()让您的应用程序在文化方面更具普遍性.当前文化发生变化时,TryParse()将解析没有问题.也TryParse()被认为没有错误的方法,因为它们由.net社区测试:).

但是在正则表达式的情况下,你应该改变你的验证表达,因此它可能与新文化无关.

你可以像这样重写代码:

private bool IsValidInput(string p)
{
    switch (this.Type)
    {
        case NumericTextBoxType.Float:
            double doubleResult;
            return double.TryParse(p, out doubleResult);
        case NumericTextBoxType.Integer:                    
        default:
            int intResult;
            return int.TryParse(p, out intResult);
    }
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以添加自己的扩展方法,使解析部分更加优雅.

public static double? TryParseInt(this string source)
{
    double result;
    return double.TryParse(source, out result) ? result : (double?)null;
}

// usage
bool ok = source.TryParseInt().HasValue;
Run Code Online (Sandbox Code Playgroud)