Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
I am creating a username validation. I am using this regex:
^[a-zA-Z0-9][a-zA-Z0-9_\-]{0,4}[a-zA-Z0-9]$

which takes input that allows lower case, upper case, numbers, hyphens, and underscores. The hyphen and underscore must not be at the start or end of the string. I do not want the username to include two consecutive hyphens or underscores, like Aquib- -qureshi or aquib_ _qureshi (spaces shown for clarity only).

Can I do this using regex or do I have to write a piece of code to look for those consecutive characters?

How to do that? Can anyone help me out with an example?

Thanks in advance.
Posted
Updated 22-Jul-18 0:09am
v2
Comments
ridoy 30-Sep-12 14:21pm    
no you don't need to use code for that..add _ _/-- with your regular expression

1 solution

^([a-zA-Z0-9](?(?!__|--)[a-zA-Z0-9_\-])+[a-zA-Z0-9])$

or
^([a-zA-Z0-9](?(?!__|--)[a-zA-Z0-9_\-]){0,4}[a-zA-Z0-9])$

to limit to 6 characters like your example.

The magic sauce is the negative lookaround assertion.

Please mark answered if I helped you. —Yvan
 
Share this answer
 
v3
Comments
ridoy 30-Sep-12 14:22pm    
yes that's the right one as i said...+5
shaikh-adil 30-Sep-12 14:30pm    
{0,4}
this will take 5 charecters right? So how 6 will be taken? I didint got you
Yvan Rodrigues 30-Sep-12 14:32pm    
No, it will take between zero and four character matches; plus the start and end characters == 6.
shaikh-adil 30-Sep-12 14:37pm    
what diffrence between your regex and this one?
Can you explain bro
^[a-zA-Z0-9]{1,5}(-[a-zA-Z0-9]{1,5}|_[a-zA-Z0-9]{1,5})?$
Yvan Rodrigues 30-Sep-12 14:46pm    
That one means:
- start with between 1 and 5 characters from the set a-z, A-Z, 0-9.
- the next character MUST be a hyphen or an underscore.
- end with between 1 and 5 characters from the set a-z, A-Z, 0-9.

- there must be between 3 and 11 characters.

Do yourself a favour and download Expresso and read the "30 Minute Regex Tutorial" on this site.

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