【问题标题】:How can I ensure that a string contains no more than 3 digits?如何确保字符串包含不超过 3 位数字?
【发布时间】:2012-10-23 12:09:17
【问题描述】:

我正在寻找可以验证我的字符串的正则表达式。字符串应该

  1. 长度为 6 到 25 个字符(允许任何字符)
  2. 不超过 3 位数字

如何做到这一点?

【问题讨论】:

  • “1:包含所有字符”是什么意思?
  • 这可能不是您要寻找的答案,但自己学习不仅会给您答案(也许会更好),还会帮助您教给其他人:regular-expressions.info/tutorial.html
  • 这意味着字符串可以包含任何可用的字符,例如,但如果有一些数字,它应该最多三个数字
  • @MarkByers 我假设他想要一个 6-25 个字符的字符串(从 A-Z),它需要包含 1-3 个数字。
  • 三位数字在一起?在任何位置?

标签: .net regex


【解决方案1】:

您可以将否定前瞻断言用作:

^(?!.*[0-9].*[0-9].*[0-9].*[0-9]).{6,25}$

See it

确保您的输入中没有 4 位数字。

【讨论】:

    【解决方案2】:

    这可以通过lookahead assertion 来实现:

    ^(?=(?:\D*\d){0,3}\D*$).{6,25}$
    

    说明:

    ^           # Start of string
    (?=         # Assert that the following can be matched here:
     (?:\D*\d)  # Any number of non-digits, followed by one digit
     {0,3}      # (zero to three times)
     \D*        # followed by only non-digits
     $          # until the end of the string
    )           # (End of lookahead)
    .{6,25}     # Match 6 to 25 characters (any characters except newlines)
    $           # End of string
    

    【讨论】:

      【解决方案3】:

      听起来你只需要排除超过三位数的字符串和不符合长度要求的字符串。

      两者都不需要正则表达式,事实上,构造一个正则表达式来匹配是很棘手的,因为数字可能会分散。

      使用"a string".Length检查字符数。

      遍历字符并使用char.IsDigit 检查位数。

      public bool IsValid(string myString)
      {
         if (myString.Length < 6 || myString.Length > 25)
            return false;
      
         int digitCount = 0;
         foreach(var ch in myString)
         {
            if(char.IsDigit(ch))
              digitCount;
         }
      
         return digitCount < 4;
      }
      

      【讨论】:

      • 你不是说'return digitCount
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 2012-01-05
      • 2022-12-05
      相关资源
      最近更新 更多