Sometimes we need to validate an email address using regex in our script in automation.
In the below code I have used "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$" pattern which means that the provided email address matches alphabets in Uppercase or Lowercase or digits, the same will match after dot(.) if provided ,zero or more time before ‘@’.
After ‘@’ it matches alphabets in Uppercase or Lowercase or digits one or more time and after dot (.) matches minimum 2 alphabets either in Uppercase or lowercase according to the requirement.
For more understanding i am splitting this regex pattern into the character classes and groups with description:
Before ‘@’ --
[_A-Za-z0-9-]+ --> Matches Uppercase or Lowercase or digits with underscore one or more time
(\\.[_A-Za-z0-9-]+)* → Matches Uppercase or Lowercase or digits with underscore zero or more time (If dot is present)
After ‘@’ --
[A-Za-z0-9-]+ -->Matches Uppercase or Lowercase or digits one or more time
(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,}) → Matches Uppercase or Lowercase or digits with underscore zero or more time followed by after dot Uppercase or Lowercase with the length of minimum 2.
You can write your own pattern according to the requirement and validate an Email address.
package Regex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegEx {
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static Pattern pattern = Pattern.compile(EMAIL_PATTERN);
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter Email1: ");
String email1 = br.readLine();
System.out.println("Enter Email2: ");
String email2= br.readLine();
Matcher matcher1 = pattern.matcher(email1);
Matcher matcher2 = pattern.matcher(email2);
if(matcher1.matches()){
System.out.println("Pattern1 matched");
}else{
System.out.println("Pattern1 did not match");
}
if(matcher2.matches()){
System.out.println("Pattern2 matched");
}else{
System.out.println("Pattern2 did not match");
}
System.out.println(matcher1.lookingAt());
System.out.println(matcher2.lookingAt());
}
}
Output:
Enter Email1: sri@gmail.com
Enter Email2: ssddss
Pattern1 matched
Pattern2 did not match
true
false
On executing the above program, user will be asked to enter an email1 and email2 at the runtime, then it will match email1 and email2 with the defined regular expression,
If the same matches with regex then Pattern1 matched will be printed else Pattern2 did not match will be printed.
“lookingAt()” method used above will return the boolean expression as true(if email1 and email2 matches with regex) or false(if email1 and email2 do not match with regex).
0 Comment(s)