使用 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

更新于:2019-11-21

5K+ 浏览量

开启您的 职业

通过完成该课程获取认证

开始
广告