Reputation: 7736
I am trying to validate user names, in Java, based on the following rules:
The regex I am using to perform validation is ^[a-z]+\.?[a-z0-9]+$
This works quite nice (there may be better ways of doing this), except now I want to allow user names that are between 3 and 10 characters long. Anywhere I try to use {3,10}
, e.g. ^([a-z]+\.?[a-z0-9]+){3,10}$
, validation fails. I am using an excellent visual regex tool and online regex tester.
The code itself is really simple; I am using the String class' matches method in Java 8. john.doe passes the regex and length validation, but j.doe does not.
Update, based on selected answer:
The Java code can be a little self-explanatory, given the complexity of the regex:
private static final String PATTERN_USERNAME_REGEX = new StringBuilder()
// the string should contain 3 to 10 chars
.append("(?=.{3,10}$)")
// the string should start with a lowercase ASCII letter
.append("[a-z]")
// then followed by zero or more lowercase ASCII letters or/and digits
.append("[a-z0-9]*")
// an optional sequence of a period (".") followed with 1 or more lowercase ASCII letters
// or/and digits (that + means you can't have . at the end of the string and ? guarantees
// the period can only appear once in the string)
.append("(?:\\\\.[a-z0-9]+)?")
.toString();
Upvotes: 3
Views: 65
Reputation: 626748
The regex you seek is
^(?=.{3,10}$)[a-z][a-z0-9]*(?:\.[a-z0-9]+)?$
In Java,
s.matches("(?=.{3,10}$)[a-z][a-z0-9]*(?:\\.[a-z0-9]+)?")
See the regex demo.
Details
^
- start of string (no need to use in String#matches
)(?=.{3,10}$)
- the string should contain 3 to 10 chars[a-z]
- a lowercase ASCII letter[a-z0-9]*
zero or more lowercase ASCII letters or/and digits(?:\.[a-z0-9]+)?
- an optional sequence of a .
followed with 1 or more lowercase ASCII letters or/and digits (that +
means you can't have .
at the end of the string and ?
guarantees the .
can only appear once in the string)$
- end of string (no need to use in String#matches
)Upvotes: 4