switch语句 - 验证子字符串

时间:2011-09-14 11:21:58

标签: c# .net switch-statement substring

字段数据有4种可接受的值类型:

 j
 47d (where the first one-two characters are between 0 and 80 and third character is d)
 9u (where the first one-two characters are between 0 and 80 and third character is u)
 3v (where the first character is between 1 and 4 and second character is v).

否则数据应视为无效。

string data = readconsole();

验证此输入的最佳方法是什么?

我正在考虑.Length和Switch子字符串检查的组合。

if (data == "j")

else if (data.substring(1) == "v" && data.substring(0,1) >=1 && data.substring(0,1) <=4)
....
else
   writeline("fail");

3 个答案:

答案 0 :(得分:4)

您可以使用与不同类型的值匹配的正则表达式:

^(j|(\d|[1-7]\d|80)[du]|[1-4]v)$

示例:

if (Regex.IsMatch(data, @"^(j|(\d|[1-7]\d|80)[du]|[1-4]v)$")) ...

正则表达式的说明:

^ matches the beginning of string
j matches the literal value "j"
| is the "or" operator
\d matches one digit
[1-7]\d matches "10" - "79"
80 matches "80"
[du] matches either "d" or "u"
[1-4] matches "1" - "4"
v matches "v"
$ matches the end of the string

答案 1 :(得分:2)

regular expression将是验证此类规则的最简洁方法。

答案 2 :(得分:1)

您可以使用正则表达式:

^(?:j|(?:[0-7]?[0-9]|80)[du]|[1-4]v)$

另一种选择是按数字和字母分割,并检查结果。这是相当长的,但从长远来看可能更容易维护:

public bool IsValid(string s)
{
    if (s == "j")
        return true;
    Match m = Regex.Match(s, @"^(\d+)(\p{L})$");
    if (!m.Success)
        return false;
    char c = m.Groups[2].Value[0];
    int number;
    if (!Int32.TryParse(m.Groups[1].Value, NumberStyles.Integer,
        CultureInfo.CurrentCulture, out number)) //todo: choose culture
        return false;
    return ((c == 'u' || c == 'd') && number > 0 && number <= 80) ||
           (c == 'v' && number >= 1 && number <= 4);
}