A regular expression for receiving alphanumeric characters (6-10 characters). NET, C #

I am creating a user registration form using C # with .NET. I have a requirement for checking user entered passwords. Validation requirements are as follows.

  • It must be alphanumeric (az, AZ, 0-9)
  • It should accept 6-10 characters (minimum 6 characters, no more than 10 characters)
  • At least 1 alphabet and number (example: stack1over )

I use regex as shown below.

 ^([a-zA-Z0-9]{6,10})$ 

It satisfies my first two conditions. It does not work when I enter only characters or numbers.

+4
source share
3 answers

Pass it through a few regular expressions if you can. It will be much cleaner than these monstrous prospects :-)

 ^[a-zA-Z0-9]{6,10}$ [a-zA-Z] [0-9] 

Although some may find this smart, you don’t have to do everything with one regular expression (or even with any regular expression, sometimes just a witness to people who want the regular expression to find numbers between 75 and 4093).

You would rather see nice clean code, for example:

 if not checkRegex(str,"^[0-9]+$") return false val = string_to_int(str); return (val >= 75) and (val <= 4093) 

or something like:

 return checkRegex(str,"^7[5-9]$|^[89][0-9]$|^[1-9][0-9][0-9]$|^[1-3][0-9][0-9][0-9]$|^40[0-8][0-9]$|^409[0-3]$") 

I know which one I would prefer to support :-)

+8
source

Use a positive lookahead

 ^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]{6,10}$ 

Looking around is also called zero-width statements. They have zero width, as are the beginning and end of the string ( ^ , $ ). The difference is that the finds will actually coincide with the symbols, but then refuse the match and return the result only: match or no match. That is why they are called "statements." They do not consume characters in a string, but only claim whether a match is possible.

The syntax to view is:

  • (?=REGEX) Positive look
  • (?!REGEX) Negative look
  • (?<=REGEX) Positive lookbehind
  • (?<!REGEX) Negative look
+7
source
 string r = @"^(?=.*[A-Za-z])(?=.*[0-9])[A-Za-z0-9]{6,10}$"; Regex x = new Regex(r); var z = x.IsMatch(password); 

http://www.regular-expressions.info/refadv.html

http://www.regular-expressions.info/lookaround.html

0
source

Source: https://habr.com/ru/post/1300150/


All Articles