2

I have been into a serious trouble with RegEx. I have to make a username regex and the requirement is as follows:

  1. Only small alphabets, numbers and underscores are allowed.
  2. The username can consist of only alphabets or only numbers or a mix of all.
  3. Underscore cannot be at the start or end.
  4. Multiple underscores in a row, are not allowed.
  5. Total username would not be more than 20 characters and less than three. (Optional. Because without regex that can be checked)

I am giving some possible examples: a_123, 1_1, amit12343, 12ami, a_457_h, abc, 456

I have already created a solution which is ^[a-z0-9][a-z0-9_]{1,18}[a-z0-9]$

In my above solution, all the requirements do suffice except multiple underscores in a row like a__a, ab___123

Can anyone please show me the correct way?

Edit 1: I have tried all the other solutions obviously before posting such a long question on StackOverflow. But all those didn't solve my problem, that's why I have asked. Multiple underscores in a row are passing with my regex which shouldn't and that's why I asked for a community help.

Edit 2: After seeing a lot of references from Revo, I got a way to create the short and crisp solution of my above scenario.

^(?=.{3,20}$)[a-z0-9]+([_][a-z0-9]+)*$

In the beginning, a positive lookahead to check the minimum and maximum character of the username, the next phase explains that alphabets, numbers are allowed more than once. After that one or more underscores are allowed but not in a row. You can check the demo.

Indranil Dutta
  • 159
  • 2
  • 14
  • Please go through both marked questions. This problem and similar ones are asked so many times before. I'm sure you will get your answer. – revo Jun 15 '18 at 06:04
  • @revo I have already seen those answers. It looks almost same but still different. Because in my username more than one underscores are allowed in the total string but multiple underscores in a row are not allowed. All other solutions are allowing only one underscore or hyphen in the whole string. That's not my need. – Indranil Dutta Jun 15 '18 at 06:08
  • Then I'm sure you didn't take a more precise look at the answers. Both accepted answers allow multiple underscores but not those in a row. – revo Jun 15 '18 at 06:11
  • 1
    @revo I have created the shortest solution. It is different from the already provided solutions. But thank you for your references. ^[a-z0-9]+([_][a-z0-9]+)*$ This is the one. Short and crisp. – Indranil Dutta Jun 15 '18 at 06:25
  • You could apply length too `^(?=.{3,20}$)[a-z0-9]+(?:_[a-z0-9]+)*$` – revo Jun 15 '18 at 06:38
  • @revo yes I already have that implemented. Thank you. – Indranil Dutta Jun 15 '18 at 06:51
  • I answered 99.999999% identical question before. Changed the close reason. – Wiktor Stribiżew Jun 15 '18 at 07:05

0 Answers0