Click here to Skip to main content
15,908,675 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
suggest an regex for username which takes input that allows lower case, upper case, numbers, and underscores. The username can start with alphabets or underscore. The underscore must not be at the end of the string. I do not want the username to include two consecutive underscores.

What I have tried:

[_a-zA-Z0-9][a-zA-Z0-9]+_?[a-zA-Z0-9]+

But the problem it fails for the username a_9
Posted
Updated 26-Aug-17 6:23am
Comments
PIEBALDconsult 26-Aug-17 12:25pm    
^[_a-zA-Z](?:[a-zA-Z0-9]|(?:(?<!_)_(?!_)))*[a-zA-Z0-9]$
Member 13379434 28-Aug-17 13:20pm    
can you suggest it in javascript?
Member 13379434 28-Aug-17 13:35pm    
And what happens if user name is 1 char?

You need to include the underscore character in the second group. You can try different patterns at RegExr: Learn, Build, & Test RegEx[^].
 
Share this answer
 
Comments
Member 13379434 26-Aug-17 12:07pm    
then a__9 also be accepted. But it repeating underscore
Richard MacCutchan 26-Aug-17 12:12pm    
Go to the link I gave you and try some different patterns.
Member 13379434 26-Aug-17 12:19pm    
it's helpful. but i can't find the solution for the above problem.
Richard MacCutchan 26-Aug-17 12:20pm    
You need to go through it step by step, adding each rule and different sample strings until you get the pattern you need.
Use the last link below to see a nice graph of your RegEx, you will understand what is wrong.
Are you sure about your constraint ?
It will make the RefEx pretty complicated.
What constraint apply if user name is 1 char? is it allowed to be '_' ?
'_a_b_c_d_e' seems legal, but your RegEx will not accept it.

Just a few interesting links to help building and debugging RegEx.
Here is a link to RegEx documentation:
perlre - perldoc.perl.org[^]
Here is links to tools to help build RegEx and debug them:
.NET Regex Tester - Regex Storm[^]
Expresso Regular Expression Tool[^]
RegExr: Learn, Build, & Test RegEx[^]
This one show you the RegEx as a nice graph which is really helpful to understand what is doing a RegEx:
Debuggex: Online visual regex tester. JavaScript, Python, and PCRE.[^]
 
Share this answer
 
Comments
Member 13379434 28-Aug-17 13:08pm    
Then can you suggest me a solution sir?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900