I\'m trying to create a regular expression to validate usernames against these criteria:
This one should do the trick:
if (Regex.IsMatch(text, @"
# Validate username with 5 constraints.
^ # Anchor to start of string.
# 1- only contains alphanumeric characters , underscore and dot.
# 2- underscore and dot can't be at the end or start of username,
# 3- underscore and dot can't come next to each other.
# 4- each time just one occurrence of underscore or dot is valid.
(?=[A-Za-z0-9]+(?:[_.][A-Za-z0-9]+)*$)
# 5- number of characters must be between 8 to 20.
[A-Za-z0-9_.]{8,20} # Apply constraint 5.
$ # Anchor to end of string.
", RegexOptions.IgnorePatternWhitespace))
{
// Successful match
} else {
// Match attempt failed
}
As much as I love regular expressions I think there is a limit to what is readable
So I would suggest
new Regex("^[a-z._]+$", RegexOptions.IgnoreCase).IsMatch(username) &&
!username.StartsWith(".") &&
!username.StartsWith("_") &&
!username.EndsWith(".") &&
!username.EndsWith("_") &&
!username.Contains("..") &&
!username.Contains("__") &&
!username.Contains("._") &&
!username.Contains("_.");
It's longer but it won't need the maintainer to open expresso to understand.
Sure you can comment a long regex but then who ever reads it has to rely on trust.......
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = Integer.parseInt(scan.nextLine());
while (n-- != 0) {
String userName = scan.nextLine();
String regularExpression = "^[[A-Z]|[a-z]][[A-Z]|[a-z]|\\d|[_]]{7,29}$";
if (userName.matches(regularExpression)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
I guess you'd have to use Lookahead expressions here. http://www.regular-expressions.info/lookaround.html
Try
^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$
[a-zA-Z0-9]
an alphanumeric THEN (
_(?!\.)
a _ not followed by a . OR
\.(?!_)
a . not followed by a _ OR
[a-zA-Z0-9]
an alphanumeric ) FOR
{6,18}
minimum 6 to maximum 18 times THEN
[a-zA-Z0-9]
an alphanumeric
(First character is alphanum, then 6 to 18 characters, last character is alphanum, 6+2=8, 18+2=20)
^(?=.{4,20}$)(?:[a-zA-Z\d]+(?:(?:\.|-|_)[a-zA-Z\d])*)+$
You can test the regex here
function isUserName(val){
let regUser=/^[a-zA-Z0-9](_(?!(\.|_))|\.(?!(_|\.))|[a-zA-Z0-9]){6,18}[a-zA-Z0-9]$/;
if(!regUser.test(val)){
return 'Name can only use letters,numbers, minimum length is 8 characters';
}
}