Java用正则表达式判断输入的电话号码格式是否正确

通过正则表达式来判断用户输入的电话号码格式是否有误:


MainDemo.java

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 输入电话号码,判断电话号码格式是否有误
 * @author 周孟军	时间:2016年7月29日 上午10:01:55 
 *
 */
public class MainDemo {
	public static void main(String[] args) {
		System.out.println("请输入您的电话号码:");
		Scanner scanner = new Scanner(System.in);
		String mobile_number = scanner.nextLine();

		boolean boo = isMobileNO(mobile_number);
		if (boo) {
			System.out.println("电话号码正确!-->" + mobile_number);
		} else {
			System.out.println("电话号码错误!***>" + mobile_number);
		}
	}

	//判断的方法
	public static boolean isMobileNO(String mobiles) {
		boolean flag = false;
		try {

			// 13********* ,15********,18*********
			Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");

			Matcher m = p.matcher(mobiles);
			flag = m.matches();

		} catch (Exception e) {
			flag = false;
		}

		return flag;
	}

}
注:输入13、15、18开头的电话号码就为正确,11位电话号码。

你可能感兴趣的:(Java)