案例一:对QQ号进行验证
要求:必须是0-15位,0不能开头,只能是数字
在没学过正则表达式,首先想到的是:
public static voidcheck()
{
String qq="0123019";int len =qq.length();if(len>=5&&len<=15)
{if(!qq.startsWith("0"))
{char[] arr=qq.toCharArray();boolean flag = true;for(int x=0;x
{if(arr[x]>='0'&&arr[x]<=9)
{
flag=false;
}
}if(flag)
{
System.out.println("QQ:"+qq);
}else{
System.out.println("出现非法字符");
}
}else{
System.out.println("不可以以0开头");
}
}else{
System.out.println("小于5或者大于15");
}
}
再优化一下,可以这么写:
public static voidcheck()
{
String qq="0123019";int len =qq.length();if(len>=5&&len<=15)
{if(!qq.startsWith("0"))
{try{long l =Long.parseLong(qq);
}catch(NumberFormatException e) {//TODO Auto-generated catch block
System.out.println("数字异常");//e.printStackTrace();
}
}else{
System.out.println("不可以以0开头");
}
}else{
System.out.println("小于5或者大于15");
}
}
}
接下来,最重要,简便的正则表达式派上用场:
public static voidregeCheck()
{
String qq= "012345";
String rege= "[1-9][0-9]{4,14}";//【1-9】代表第一位只能是1-9的数字//【0-9】{4,14}表示后边是0-0的数字,并且是在4-14位之间
boolean flag =qq.matches(rege);
System.out.println(flag);if(flag){
System.out.println(qq+" is OK");
}else{
System.out.println(qq+" is error!");
}
}
public static voidgetMails()
{//System.out.println("getMails");
try{
URL url= new URL("https://mail.qq.com/cgi-bin/frame_html?sid=tSk9WTbKfPKOCCVy&r=0cf16a3eabaaac83f3df241863066baf");
URLConnection conn= null;try{
conn=url.openConnection();
System.out.println("getMails");
}catch(IOException e1) {//TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader bufIn= nul