-1

我为值做了一个Regex过滤器。double

例如,一个TextBox包含音量,我将其regex用于

double ConvertToDouble(String input)
{
    // Matches the first numebr with or without leading minus.
    Match match = Regex.Match(input, "[+-]?\\d*\\.?\\d+");

    if (match.Success)
    { 
        return Double.Parse(match.Value);
    }
    return 0; // Or any other default value.
}

00,5进入TextBox.

4

2 回答 2

6

我建议使用double.TryParse并完全摆脱正则表达式:

// static : we don't use "this" in the method
static double ConvertToDouble(String input)
{
    // if we can parse input...
    if (double.TryParse(input, out double result))
        return result; // ...return the result of the parsing
    else
        return 0.0;    // otherwise 0.0 or any default value
}
于 2019-10-01T08:01:56.120 回答
0

您的正则表达式目前仅匹配用点 ( .) 指定的小数,而不是逗号 ( ,)。

您可以使用以下方法修改正则表达式以接受:

[+-]?\d*[\,\.]?\d+

在您的代码中:

Match match = Regex.Match(input, @"[+-]?\d*[\.\,]?\d+");

这将匹配0,50.5

于 2019-10-01T07:59:29.380 回答