java中我们会常用一些判断如IP、电子邮箱、电话号码的是不是符合,那么我们怎么来判断呢,答案就是利用正则表达式来判断了,因为本人对正则表达式没有太深的研究,所有感兴趣的朋友可以自行百度。我这就给基本的判断,废话不多说,下面就是上代码。IP地址的判断方法
正则表达式判断ip是否合法,并把ip转为整数(点中间可以有空格):
package com.atown;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestSortAlgrim {
public static void main(String[] args) {
TestSortAlgrim testSortAlgrim = new TestSortAlgrim();
String ip = " 172 . 168 . 5. 1 ";
Long result = testSortAlgrim.ipToInt(ip);
System.out.println(result);
}
public Long ipToInt(String ip){
StringBuffer sb = new StringBuffer();
StringBuffer intToBianary = new StringBuffer();
Long result = 0L;
if(isIpValid(ip)){//判断 ip 是否合法
char[] chars = ip.toCharArray();
int j=3;
String regx_num = "[0-9]";
String regx_chac = "[. ]";
Pattern pattern_chac = Pattern.compile(regx_chac);
Pattern pattern_num = Pattern.compile(regx_num);
for (int i=0;i<chars.length;i++){
Matcher matcher_num = pattern_num.matcher(String.valueOf(chars[i]));
Matcher matcher_chac = pattern_chac.matcher(String.valueOf(chars[i]));
if(matcher_num.find()){
sb.append(chars[i]);
}else if(matcher_chac.find()&&sb.length()>0){
result += (Long.parseLong(String.valueOf(sb))<<j*8);
j--;
sb.delete(0,sb.length());
}
}
if(sb.length()>0){
result += Long.parseLong(String.valueOf(sb));
}
return result;
}
return 0L;
}
public boolean isIpValid(String ip){
if(null==ip||"".equals(ip)){
return false;
}
String rexp = "^\\s*(1\\d{2}\\s*|\\s*2[0-4]\\d\\s*|\\s*25[0-5]\\s*|\\s*[1-9]\\d\\s*|\\s*[1-9]\\s*|\\s*)\\."
+ "(\\s*1\\d{2}\\s*|\\s*2[0-4]\\d\\s*|\\s*25[0-5]\\s*|\\s*[1-9]\\d\\s*|\\s*\\d\\s*)\\."
+ "(\\s*1\\d{2}\\s*|\\s*2[0-4]\\d\\s*|\\s*25[0-5]\\s*|\\s*[1-9]\\d\\s*|\\s*\\d\\s*)\\."
+ "(\\s*1\\d{2}\\s*|\\s*2[0-4]\\d\\s*|\\s*25[0-5]\\s*|\\s*[1-9]\\d\\s*|\\s*\\d\\s*)$";
Pattern pat = Pattern.compile(rexp);
Matcher mat = pat.matcher(ip);
if(mat.find())
return true;
else
return false;
}
}
判断是否是正确的邮箱地址
public static boolean orEmail(String email) {
if (email == null || "".equals(email)) return false;
String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
return email.matches(regex);
}
判断是否是手机号码
public static boolean orPhoneNumber(String phoneNumber) {
if (phoneNumber == null || "".equals(phoneNumber))
return false;
String regex = "^1[3|4|5|8][0-9]\\d{8}$";
return phoneNumber.matches(regex);
}
|
|