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
- First let's take username as input
Scanner sc = new Scanner(System.in); String userName = sc.nextLine();
- Creating a regex pattern for username validation.
String regularExpression= "^[A-Za-z][A-Za-z0-9_]{7,29}$";
- A valid username should start with an alphabet so, [A-Za-z].
- 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 userName = sc.nextLine();
String regularExpression = "^[A-Za-z][A-Za-z0-9_]{7,29}$";
if (userName.matches(regularExpression)) {
System.out.println("Valid");
} else {
System.out.println("Invalid");
}
}
}
Hurray! We have successfully learnt validating username using regex in java today.π
Drop a like and do share your valuable feedback in comments!
I would love to connect with you through Twitter, LinkedIn, Github.