I have been into a serious trouble with RegEx. I have to make a username regex and the requirement is as follows:
- Only small alphabets, numbers and underscores are allowed.
- The username can consist of only alphabets or only numbers or a mix of all.
- Underscore cannot be at the start or end.
- Multiple underscores in a row, are not allowed.
- 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.