1

I would like to have a regular expression that checks if a string contains upper and lowercase letters, numbers, and underscores as well as a character limit. These are the only Types allowed in the string.

However, the string does not have to contain all of the specified arguments.

Meaning that the string could be alphanumeric or alphanumeric with underscores or just numbers or just letters ETC.

I followed the suggestions provided here: Regular Expression for alphanumeric and underscores

and came up with the following Expression: ^([a-zA-Z0-9_]){3,15}$

So the Question is: What Is wrong with my REGEX?

KING
  • 938
  • 8
  • 26

1 Answers1

1

Your regex - ^([a-zA-Z0-9_]){3,15}$ - matches a whole string that is 3 to 15 chars long and only consists of ASCII letters, digits or _ symbol.

It appears you want to detect a string that contains at least 3 characters from the specified ranges (letter/digit/underscore).

You may use

[a-zA-Z0-9_](?:[^a-zA-Z0-9_]*[a-zA-Z0-9_]){2}

Or a less linear:

(?:[^a-zA-Z0-9_]*[a-zA-Z0-9_]){3}

Use the patterns with Regex.IsMatch, this method allows partial matches.

Details:

  • [a-zA-Z0-9_] - matches a single char from the ranges specified
  • (?: - start of a non-capturing group matching a sequence of....
    • [^a-zA-Z0-9_]* - 0+ chars other than those defined in the negated character class
    • [a-zA-Z0-9_] - a char from the ranges specified
  • ){2} - ....2 times exactly.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563