【问题标题】:switch statement - validate substringsswitch 语句 - 验证子字符串
【发布时间】:2011-09-14 11:21:57
【问题描述】:

字段数据有 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).

否则数据将被视为无效。

字符串数据 = 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");

【问题讨论】:

  • 我知道语法无效,必须将字符串转换为整数和 console.writeline().etc 但你明白了。

标签: c# .net switch-statement substring


【解决方案1】:

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

^(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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      可以使用正则表达式:

      ^(?: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);
      }
      

      【讨论】:

      • 刚刚看到编辑,它有效 - 谢谢!赞成。 Guffa 几分钟前刚开始工作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      相关资源
      最近更新 更多