gpt4 book ai didi

c# - c# 中货币值(value)的 RegEx 验证

转载 作者:行者123 更新时间:2023-11-30 14:52:11 24 4
gpt4 key购买 nike

必须接受:

1,111.11 or 1000.00

不得接受:

,111 or 1,11,11 or 1.00.00

目前我有这段代码:

if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
{
MessageBox.Show("Please enter only numbers.");
//textBox1.Text.Remove(textBox1.Text.Length - 1);
textBox1.Text = string.Empty;
}

只接受数字

最佳答案

与其尝试使用 RegEx 来验证自己,不如使用一些内置功能来获得所需的结果。

一种方法是:

var culture = CultureInfo.CreateSpecificCulture("en-US");
decimal currency;
if (Decimal.TryParse(textBox1.text, NumberStyles.Currency, culture, out currency))
{
// Its a valid currency value
}
else {
// NOt a valid currency.
MessageBox.Show("Please enter a valid currency.");
}

这适用于您不想将应用程序用于不同文化的情况(当然前提是您不对“en-US”进行硬编码)。

阅读更多关于 Decimal.TryParse here 的信息.

关于c# - c# 中货币值(value)的 RegEx 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32366227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com