Skip to main content
 首页 » 编程设计

c#之根据自定义格式验证字符串

2024年02月06日22小虾米

我想根据自定义格式验证字符串:___.___ 或 ___,___,3 个数字后跟一个点或逗号后跟 3 个数字 (例如 123.456 或 123,456)。

目前,我有以下代码:

string InputText = "123.456" 
bool result, result1, result2; 
int test, test2; 
result = Int32.TryParse(InputText.Substring(0, 3), out test); 
result1 = (InputText[3] == '.' || InputText[3] == ',') ? true : false; 
result2 = Int32.TryParse(InputText.Substring(4, 3), out test2); 
 
if (result == false || result1 == false || result2 == false) 
{ 
    Console.WriteLine("Error! Wrong format."); 
} 

这工作得很好,但是,这似乎相当低效且不必要地复杂;有替代方案吗?

请您参考如下方法:

有替代方案吗?是的,您可以使用 Regex.IsMatch 来执行此操作。

String s = "123.456"; 
if (!Regex.IsMatch(s, @"^\d{3}[.,]\d{3}$")) { 
    Console.WriteLine("Error! Wrong format."); 
} 

解释:

^        # the beginning of the string 
 \d{3}   #   digits (0-9) (3 times) 
 [.,]    #   any character of: '.', ',' 
 \d{3}   #   digits (0-9) (3 times) 
$        # before an optional \n, and the end of the string