Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to allow only some characters in .net

Tags:

c#

.net

regex

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
  }
like image 435
Gurucharan Balakuntla Maheshku Avatar asked Dec 29 '22 04:12

Gurucharan Balakuntla Maheshku


1 Answers

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.")
like image 141
cdhowie Avatar answered Jan 12 '23 00:01

cdhowie