English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Проверка действительности адреса электронной почты с помощью Java регулярного выражения

To verify that the given input string is a valid email ID, use the following regular expression to match the given input string to match the email ID-

"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$"

Where,

  • ^ matches the beginning of the sentence.

  • [a-zA-Z0-9 + _.-] matches a character from the English alphabet (two cases), the digit "+", "_", "." before the "@" symbol.

  • + indicates the repetition of the above character set once or more.

  • @ matches itself.

  • [a-zA-Z0-9.-] matches a character from the English alphabet (two cases), the digit "." after the "@" symbol.

  • $ represents the end of the sentence.

Example

import java.util.Scanner;
public class ValidatingEmail {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your Email: ");
      String phone = sc.next();
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Match the given number with the regular expression
      boolean result = phone.matches(regex);
      if(result) {
         System.out.println("Given email-id is valid");
      } else {
         System.out.println("Given email-id is not valid");
      }
   }
}

Вывод 1

Enter your Email:
[email protected]
Given email-id is valid

Вывод 2

Enter your Email:
[email protected]
Given email-id is not valid

Пример 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Введите ваше имя:");
      String name = sc.nextLine();
      System.out.println("Введите ваш идентификатор электронной почты:");
      String phone = sc.next();
      //Прием регулярного выражения для действительного идентификатора электронной почты
      String regex = "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$";
      //Создание объекта Pattern
      Pattern pattern = Pattern.compile(regex);
      //Создание объекта Matcher
      Matcher matcher = pattern.matcher(phone);
      //Проверка действительности указанного номера
      if(matcher.matches()) {
         System.out.println("Указанный идентификатор электронной почты действителен");
      } else {
         System.out.println("Указанный идентификатор электронной почты недействителен");
      }
   }
}

Вывод 1

Введите ваше имя:
vagdevi
Введите ваш идентификатор электронной почты:
[email protected]
Указанный идентификатор электронной почты действителен

Вывод 2

Введите ваше имя:
raja
Введите ваш идентификатор электронной почты:
[email protected]
Указанный идентификатор электронной почты недействителен
Вам может понравиться