Marlon
Marlon

Reputation: 20322

C# Regex for a username with a few restrictions

Similar to this topic.

I am trying to validate a username with the following restrictions:

Edit:

Been stumped for a while. I'm new to regex.

Upvotes: 6

Views: 7088

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283901

As an optimization to Mark's answer:

^(?=.{3,15}$)([A-Za-z0-9][._()\[\]-]?)*$

Explanation:

(?=.{3,15}$)                   Must be 3-15 characters in the string
([A-Za-z0-9][._()\[\]-]?)*   The string is a sequence of alphanumerics,
                               each of which may be followed by a symbol

This one permits Unicode alphanumerics:

^(?=.{3,15}$)((\p{L}|\p{N})[._()\[\]-]?)*$

This one is the Unicode variant, plus uses non-capturing groups:

^(?=.{3,15}$)(?:(?:\p{L}|\p{N})[._()\[\]-]?)*$

Upvotes: 16

Mark Byers
Mark Byers

Reputation: 839144

It is not so clean to express a set of unrelated rules in a single regular expression, but it can be done by using lookaround assertions (Rubular):

@"^(?=[A-Za-z0-9])(?!.*[._()\[\]-]{2})[A-Za-z0-9._()\[\]-]{3,15}$"

Explanation:

(?=[A-Za-z0-9])            Must start with a letter or number
(?!.*[._()\[\]-]{2})       Cannot contain two consecutive symbols
[A-Za-z0-9._()\[\]-]{3,15} Must consist of between 3 to 15 allowed characters

You might want to consider if this would be easier to read and more maintable as a list of simpler regular expressions, all of which must validate successfully, or else write it in ordinary C# code.

Upvotes: 13

Related Questions