C# 检查有效的字符串格式

C# 检查有效的字符串格式,c#,string,validation,formatting,C#,String,Validation,Formatting,我试图建立一个有效的系统,它检查字符串的格式是否正确 所需格式只能包含数字和破折号-,并且可以按如下顺序排序***-***-***-***-***-***-3-2-5-2-1。 例如,978-14-08855-65-2 通过更改格式键@“^([\w]+)@([\w])\([\w]+)$”,我是否可以像使用电子邮件检查系统一样使用Regex 电子邮件检查代码为 public static bool ValidEmail(string email, out string error) { e

我试图建立一个有效的系统,它检查字符串的格式是否正确

所需格式只能包含数字和破折号
-
,并且可以按如下顺序排序
***-***-***-***-***-***-
3-2-5-2-1。 例如,978-14-08855-65-2

通过更改格式键
@“^([\w]+)@([\w])\([\w]+)$”,我是否可以像使用电子邮件检查系统一样使用
Regex

电子邮件检查代码为

public static bool ValidEmail(string email, out string error)
{
    error = "";
    string regexEmailCOM = @"^([\w]+)@([\w])\.([\w]+)$";            // allows for .com emails
    string regexEmailCoUK = @"^([\w]+)@([\w])\.([\w]+)\.([\w]+)$";  // this allows fo .co.uk emails
    var validEmail = new Regex(email);

    return validEmail.IsMatch(regexEmailCOM) || validEmail.IsMatch(regexEmailCoUK) && error == "") // if the new instance matches with the string, and there is no error
}

Regex确实非常适合这种情况

一种可能的表述是:

^\d{3}-\d\d-\d{5}-\d\d-\d$
这正好匹配由
-
分隔的5组数字(
\d
)。使用花括号设置固定的重复次数