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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9107673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:58:45  来源:igfitidea点击:

Validate float number using RegEx in C#

c#wpfregexvalidation

提问by John Smith

I am trying to make a Numeric only TextBoxin WPF and I have this code for it:

我正在尝试仅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
}

When I set the type to Integer, it works well, but for Float, it does not.

当我将类型设置为 Integer 时,它运行良好,但对于 Float,则不行。

I can use so many NumericTextBoxcontrols out there, but I was wondering why this one is not working?

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

采纳答案by Andrew Cooper

Try this:

尝试这个:

@"^[0-9]*(?:\.[0-9]*)?$"

You need to escape the period. And making the period and decimal part optional is probably a good idea.

你需要逃离这个时期。使句点和小数部分可选可能是一个好主意。

If you need to handle negative values you can add -?before the first [0-9]in each pattern.

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

Update

更新

Tested as follows:

测试如下:

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

results in

结果是

False 
True 
True 
True 
False 

回答by Rob Smyth

Check out the TryParsestatic methods you will find on double, float, and int.

查看TryParse您将在 double、float 和 int 上找到的静态方法。

They return true if the string can be parsed (by the Parsemethod).

如果可以(通过Parse方法)解析字符串,则它们返回 true 。

回答by Dmitrii Lobanov

I urge you to use Double.TryParse()method instead of regex validation. Using TryParse()let your application to be a bit more universal in terms of culture. When current culture changes, TryParse()will parse with no problem. Also TryParse()methods believed to have no bugs as they were tested by .net community :).

我敦促您使用Double.TryParse()方法而不是正则表达式验证。使用TryParse()让您的应用程序在文化方面更加通用。当当前文化发生变化时,TryParse()将毫无问题地解析。还有一些TryParse()方法被认为没有错误,因为它们已经过 .net 社区的测试:)。

But in case of regex your should change your validation expression hence it could be no relevant to new culture.

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

You can rewrite code like this:

您可以像这样重写代码:

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

You can even add your own extension methods to make parsing part more elegant.

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

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

// usage
bool ok = source.TryParseInt().HasValue;

回答by Berezh

[-+]?\d+(.\d+)?

[-+]?\d+(.\d+)?

The most simple regex for float. It it doesn't match the cases '123.' or '.123'.

最简单的浮动正则表达式。它与案例“123”不匹配。或“.123”。

Also, you should look on context culture:

此外,您应该查看上下文文化:

CultureInfo ci = CultureInfo.CurrentCulture;
var decimalSeparator = ci.NumberFormat.NumberDecimalSeparator;
var floatRegex = string.Format(@"[-+]?\d+({0}\d+)?", decimalSeparator);

回答by Ramesh

I tried the solution approved above, found that it will fail if user enters a dot only @"^[0-9]*(?:\.[0-9]*)?$".

我尝试了上面批准的解决方案,发现如果用户只输入一个点它会失败 @"^[0-9]*(?:\.[0-9]*)?$"

So, I modified it to:

所以,我将其修改为:

@"^[0-9]*(?:\.[0-9]+)?$"

回答by Ananda

This is a code I came up by mixing replies from @Andrew Cooper and @Ramesh. Added the dictionary code so any body thinking of testing the code can run as many test cases the easy way.

这是我通过混合@Andrew Cooper 和@Ramesh 的回复得出的代码。添加了字典代码,因此任何想测试代码的机构都可以以简单的方式运行尽可能多的测试用例。

//greater than or equal to zero floating point numbers
Regex floating = new Regex(@"^[0-9]*(?:\.[0-9]+)?$");
        Dictionary<string, bool> test_cases = new Dictionary<string, bool>();
        test_cases.Add("a", floating.IsMatch("a"));
        test_cases.Add("a.3", floating.IsMatch("a.3"));
        test_cases.Add("0", floating.IsMatch("0"));
        test_cases.Add("-0", floating.IsMatch("-0"));
        test_cases.Add("-1", floating.IsMatch("-1"));
        test_cases.Add("0.1", floating.IsMatch("0.1"));
        test_cases.Add("0.ab", floating.IsMatch("0.ab"));

        test_cases.Add("12", floating.IsMatch("12"));
        test_cases.Add(".3", floating.IsMatch(".3"));
        test_cases.Add("12.3", floating.IsMatch("12.3"));
        test_cases.Add("12.3.4", floating.IsMatch("12.3.4"));
        test_cases.Add(".", floating.IsMatch("."));

        test_cases.Add("0.3", floating.IsMatch("0.3"));
        test_cases.Add("12.31252563", floating.IsMatch("12.31252563"));
        test_cases.Add("-12.31252563", floating.IsMatch("-12.31252563"));

        foreach (KeyValuePair<string, bool> pair in test_cases)
        {
            Console.WriteLine(pair.Key.ToString() + "  -  " + pair.Value);
        }