Β·

Hello Everyone!π

Regex is one of the topics where almost every developer takes time in the beginning. So, let's practice it today by creating the regex pattern to validate a username. Let's begin!π

Before solving, if you are not aware of syntax for writing regular expressions do check it here!

I have taken this question from Hackerrank. Let's solve it.πͺ

I recommend you to try before seeing the solution.

### πSolution

1. First let's take username as input
``````Scanner sc = new Scanner(System.in);
``````
2. Creating a regex pattern for username validation.
``````String regularExpression= "^[A-Za-z][A-Za-z0-9_]{7,29}\$";
``````
• All other characters can be alphabets, numbers or an underscore so, [A-Za-z0-9_].
• Since length constraint was given as 8-30 and we had already fixed the first character, so we give {7,29}.
• We use `^` and `\$` to specify the beginning and end of matching.

3.Now, to check the username against the regular expression.

``````if (userName.matches(regularExpression)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
``````
``````Input:
Laasya_Setty
1Hashnode
Output:
Valid
Invalid
``````

### Final Code

``````import java.util.regex;
import java.util.Scanner;
public class Solution {

public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String regularExpression = "^[A-Za-z][A-Za-z0-9_]{7,29}\$";
System.out.println("Valid");
} else {
System.out.println("Invalid");
}

}
}
``````

Hurray! We have successfully learnt validating username using regex in java today.π