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

时间:2014-08-02 16:09:33

标签: c# regex string validation format

我想根据自定义格式验证字符串:___.______,___,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.");
}

这很好用,但是,这似乎效率低下且不必要的复杂;有替代品吗?

3 个答案:

答案 0 :(得分:2)

有替代方案吗?是的,您可以使用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

答案 1 :(得分:1)

验证3个数字后跟一个点或逗号后跟3个数字的模式是,

^\d{3}[,.]\d{3}$

DEMO

答案 2 :(得分:1)

Aditional to Avinash答案如果您想捕获与格式匹配的数字,您可以使用以下正则表达式:

\b(\d{3}[.,]\d{3})\b

<强> Working demo

enter image description here

相关问题