简体   繁体   English

使用C#RegularExpressions验证用户输入

[英]Validate user input using C# RegularExpressions

How to Validate numerical input, max length limited 3 and should not start with zero characters (010, 001 should invalidate). 如何验证数字输入,最大长度限制为3,并且不应以零个字符开头(010、001应该无效)。 I used C# regex.IsMatch() with following regex ([1-9]|[1-9][0-9]|[1-9][0-9][0-9])* . 我将C# regex.IsMatch()与以下正则表达式([1-9]|[1-9][0-9]|[1-9][0-9][0-9])* But it validating inputs start with zeros. 但是它会验证输入从零开始。 How to resolve this..? 如何解决这个..?

You can omit the alternations by repeating a character class 0 - 2 times and you should use anchors to assert the start ^ and the end $ of the string. 您可以通过重复字符类0-2次来省略替换,并且应该使用锚点来声明字符串的开始^和结束$

^[1-9][0-9]{0,2}$
  • ^ Start of string ^字符串开头
  • [1-9] Match a digit 1-9 [1-9]匹配数字1-9
  • [0-9]{0,2} Match 0, 1 or 2 times a digit 0-9 [0-9]{0,2}将数字0、1或2匹配0-9
  • $ Assert end of the string $字符串结尾

Usage: 用法:

bool isMatch = Regex.IsMatch("100", @"^[1-9][0-9]{0,2}$");

Regex demo 正则表达式演示

Regex are great sure. 正则表达式非常确定。 Note that you could achieve this easily without any regex: 请注意,无需任何正则表达式即可轻松实现此目的:

static bool IsValid(string input)
{
    return !string.IsNullOrEmpty(input)
        && input.Length < 3 && !input.StartsWith("0") && input.All(char.IsDigit); 
}

Try it online 在线尝试

I'd be more specific with this one: 我会更具体一点:

^((?!(0))[0-9]{0,3})$ 

Explanations: 说明:

  • 1st one is not 0 & i want maximum 3 digits between 0 and 9. 第一个不是0,我想在0到9之间最多3个数字。

[1-9][0-9]{2}$

This would work as per your requirement. 这将根据您的要求工作。 testes on regex buddy with following test cases 正则表达式好友的睾丸,以下测试案例

  1. 001 Fail 001失败
  2. 1000000 Fail 1000000失败
  3. 900 Pass 900张
  4. 010 fail 010失败

您可以使用^[1-9][0-9]{0,2}$ ,不允许以零开头

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM