Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java 정규식을 사용하여 유효한 휴대폰 번호를 확인하는 프로그램

<시간/>

다음 정규식을 사용하여 유효한 휴대폰 번호를 일치시킬 수 있습니다 -

"\\d{10}"
  • 유효한 휴대전화 번호는 일반적으로 10자리입니다(인도).
  • 메타문자 "\d "는 0에서 9까지의 숫자와 일치합니다.
  • 한정사 ex{n}는 ex의 n번 반복을 의미합니다.

예시 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PhoneNumberExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Enter your Phone number: ");
      String phone = sc.next();
      //Regular expression to accept valid phone number
      String regex = "\\d{10}";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(phone);
      //Verifying whether given phone number is valid
      if(matcher.matches()) {
         System.out.println("Given phone number is valid");
      } else { 
         System.out.println("Given phone number is not valid");
      }
   }
}

출력 1

Enter your name:
krishna
Enter your Phone number:
9848022338
Given phone number is valid

출력 2

Enter your name:
krishna
Enter your Phone number:
5465
Given phone number is not valid

출력 3

Enter your name:
krishna
Enter your Phone number:
984802354655
Given phone number is not valid

예시 2

import java.util.Scanner;
public class Test {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your Phone number: ");
      String phone = sc.next();
      //Regular expression to accept valid phone number
      String regex = "\\d{10}";
      //Matching the given phone number with regular expression
      boolean result = phone.matches(regex);
      if(result) {
         System.out.println("Given phone number is valid");
      } else {
         System.out.println("Given phone number is not valid");
      }
   }
}

출력 1

Enter your Phone number:
9848022338
Given phone number is valid

출력 2

Enter your Phone number:
123
Given phone number is not valid

출력 3

Enter your Phone number:
123654788755
Given phone number is not valid