开发者

C# Regex for a username with a few restrictions

Similar to t开发者_如何学Chis topic.

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

  • Must start with a letter or number
  • Must be 3 to 15 characters in length
  • Symbols include: . - _ ( ) [ ]
  • Symbols cannot be adjacent, but letters and numbers can

Edit:

  • Letters and numbers are a-z A-Z 0-9

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


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})[._()\[\]-]?)*$


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜