[英]Check for the string with decimal place seperated by comma - C#
I need to check this format; 我需要检查这种格式;
1.234.567,89
1.234.567,89
Only one comma is permitted for the Entry. 条目只能使用一个逗号。
Current code 当前代码
Regex.Match(((TextChangedEventArgs)e).NewTextValue, @"^[0-9]+(\,[0-9]+)?$");
How can I achieve this? 我该如何实现?
You should not use regex to check if a string can be parsed to a decimal
/ double
. 您不应该使用正则表达式来检查字符串是否可以解析为
decimal
/ double
。 Use decimal.TryParse
(or double.TryParse
): 使用
decimal.TryParse
(或double.TryParse
):
string moneyText = "1.234.567,89";
var myCulture = new CultureInfo("de-DE");
decimal money;
bool validFormat = decimal.TryParse(moneyText, NumberStyles.Currency, myCulture, out money);
if (validFormat)
Console.WriteLine("Valid format, parsed value was " + money.ToString("C"));
Use regex to enforce possibilities by using non capturing lookaheads ( ?=
?!
) which we can enforce all rules before a match . 使用表达式使用非捕获向前看符号来执行的可能性(
?=
?!
我们可以在比赛之前执行的所有规则。
Rules are 规则是
These patterns are commented so use the option IgnorePatternWhitespace
or remove comments and join on one line. 这些模式带有注释,因此请使用选项
IgnorePatternWhitespace
或删除注释并加入一行。
Comma Required 需要逗号
^
(?=[\d\.,]+\Z) # Only allow decimals a period or a comma.
(?=.*,) # Enforce that there is a comma ahead.
(?!.*\.\.) # Fail match if two periods are consecutive.
.+ # All rules satisfied, begin matching
$
Comma and following value optional 逗号和以下值可选
^
(?=[\d\.,]+\Z) # Only allow decimals a period or a comma.
(?!.*\.\.) # Fail match if two periods are consecutive.
[\d.]+ # All rules satisfied, begin matching
(,\d+)? # If comma found, allow it but then only have decimals
$ # This ensures there are no more commas and match will fail.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.