Username cannot contain repeating underscore or period

regex

Solution

This one is the one you need:

^(?:[a-zA-Z0-9]|([._])(?!\1)){5,20}$

Edit live on Debuggex

You can have a demo of what it matches here.

"Either an alphanum char (`[a-zA-Z0-9]`), or (`|`) a dot or an underscore (`[._]`), but that isn't followed by itself (`(?!\1)`), and that from 5 to 20 times (`{5,20}`)."

`(?:X)` simply is a non-capturing group, i.e. you can't refer to it afterwards using `\1`, `$1` or `?1` syntaxes.

`(?!X)` is called a negative lookahead, i.e. literally "which is not followed by X".

`\1` refers to the first capturing group. Since the first group `(?:...){5,20}` has been set as non-capturing (see #1), the first capturing group is `([._])`.

`{X,Y}` means from X to Y times, you may change it as you need.

Problem

I have always struggled with these darn things. I recall a lecturer telling us all once that if you have a problem which requires you use regular expressions to solve it, you in fact now have 2 problems. Well, I certainly agree with this. Regex is something we don't use very often but when we do its like reading some alien language (well for me anyway)... I think I will resolve to getting the book and reading further. The challenge I have is this, I need to validate a username based on the following criteria: - can contain letters, upper and lower - can contain numbers - can contain periods (`.`) and underscores (`_`) - periods and underscores cannot be consecutive i.e. `__` `..` are not allowed but `._._` would be valid. - a maximum of 20 characters in total So far I have the following : `^[a-zA-Z_.]{0,20}$` but of course it allows repeat underscores and periods. Now, I am probably doing this all wrong starting out with the set of valid characters and max length. I have been trying (unsuccessfully) to create some look-around or look-behind or whatever to search for invalid repetitions of period (`.`) and underscore (`_`) not sure what the approach or methodology to break down this requirement into a regex solution is. Can anyone assist with a recommendation / alternative approach or point me in the right direction?

Original source