简体   繁体   English

检查以逗号分隔的小数点后的字符串-C#

[英]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 规则是

  • Only numbers, a comma or periods, a general rule. 仅数字,逗号或句点,一般规则。
  • Only allow one comma 只允许一个逗号
  • Enforce a comma 强制逗号
  • Don't allow two consecutive periods. 不允许连续两个时期。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM