Reputation: 20322
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
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
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