Java regular expression for UserName with length range
<p>I am writing a regular expression to validate UserName.</p>

<p><strong>Here is the rule:</strong></p>

<ul>
<li>Length: 6 - 20 characters</li>
<li>Must start with letter a-zA-Z</li>
<li>Can contains a-zA-Z0-9 and dot(.)</li>
<li>Can't have 2 consecutive dots</li>
</ul>

<p>Here is what I tried:</p>

<pre><code>public class TestUserName {

    private static String USERNAME_PATTERN = "[a-z](\\.?[a-z\\d]+)+";
    private static Pattern pattern = Pattern.compile(USERNAME_PATTERN, CASE_INSENSITIVE);

    public static void main(String[] args) {
        System.out.println(pattern.matcher("user.name").matches()); // true
        System.out.println(pattern.matcher("user.name2").matches()); // true
        System.out.println(pattern.matcher("user2.name").matches()); // true

        System.out.println(pattern.matcher("user..name").matches()); // false
        System.out.println(pattern.matcher("1user.name").matches()); // false
    }
}
</code></pre>

<p>The pattern I used is good but no length constraint.</p>

<p>I tried to append {6,20} constraint to the pattern but It failed.</p>

<pre><code>"[a-z](\\.?[a-z\\d]+)+{6,20}" // failed pattern to validate length
</code></pre>

<p>Anyone has any ideas?</p>

<p>Thanks!</p>