检查字符串格式

9

如何使用最少的C#代码来检查一个字符串是否符合格式#-#####(1个数字,一个短横线,然后5个数字)。

我认为正则表达式可以快速完成这个任务(但是我希望我知道正则表达式)。

下面是一个示例:

public bool VerifyBoxNumber (string boxNumber)
{
   // psudo code
   if (boxNumber.FormatMatch("#-#####")
      return true;
   return false;
}

如果您知道真正能使上述比较生效的代码,请添加答案。
3个回答

19
private static readonly Regex boxNumberRegex = new Regex(@"^\d-\d{5}$");

public static bool VerifyBoxNumber (string boxNumber)
{
   return boxNumberRegex.IsMatch(boxNumber);
}

7
return Regex.IsMatch(boxNumber, @"^\d-\d{5}$");

5
"

^\d-\d{5}$

"是一个正则表达式,它只匹配这种模式。

哇,32秒内出现了3个相同的正则表达式! - LarsH
想象一下,如果有3个完全不同的正则表达式,那将是多么糟糕的情况。 - MusiGenesis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接