开发者

Regular expression to allow only some characters in .net

I was just working on some validation and was stuck up on this though :( I want a text which contains only [a-z][A-Z][0-9][_] .

It should accept any开发者_运维技巧 of the above characters any number of times in any order. All other characters marks the text as invalid.

I tried this but it is not working !!

  {
        ......

        Regex strPattern = new Regex("[0-9]*[A-Z]*[a-z]*[_]*");

        if (!strPattern.IsMatch(val))
        {
            return false;
        }

        return true
  }


You want this:

Regex strPattern = new Regex("^[0-9A-Za-z_]*$");

Your expression does not work because:

  • It will accept any number of digits, followed by any number of uppercase letters, followed by any number of lowercase letters, followed by any number of underscores. For example, an underscore followed by a number would not match.
  • Your pattern is not anchored using the ^ and $ characters. This means that every string will match, because every string contains zero or more of the specified characters. (For example, the string "!@#$" contains zero numbers, etc.!) Anchoring the expression to the start and end of the string means that the entire string much match the entire expression or the match will fail.
  • This pattern will still accept a zero-length string as valid. If you would like to enforce that the string be at least one character, change the * near the end of the expression to +. (* means "0 or more of the previous token" while + means "1 or more of the previous token.")


Try this:

new Regex("[0-9A-Za-z_]*");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜