Java正则表达式(二)、常用正则工具类(二)

2014-11-24 08:34:35 · 作者: · 浏览: 5
失败返回false
*/
public static boolean checkBirthday(String birthday) {
String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}";
return Pattern.matches(regex,birthday);
}

/**
* 验证URL地址
* @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960 或 http://www.csdn.net:80
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkURL(String url) {
String regex = "(https ://(w{3}\\.) ) \\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5}) (/\\w*)*(\\ (.+=.*) (&.+=.*) ) ";
return Pattern.matches(regex, url);
}

/**
* 匹配中国邮政编码
* @param postcode 邮政编码
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkPostcode(String postcode) {
String regex = "[1-9]\\d{5}";
return Pattern.matches(regex, postcode);
}

/**
* 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)
* @param ipAddress IPv4标准地址
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkIpAddress(String ipAddress) {
String regex = "[1-9](\\d{1,2}) \\.(0|([1-9](\\d{1,2}) ))\\.(0|([1-9](\\d{1,2}) ))\\.(0|([1-9](\\d{1,2}) ))";
return Pattern.matches(regex, ipAddress);
}

}
单元测试类完整代码:
[java]
/**
* 正则表达式工具类测试
*/
public class RegexUtilsTest {

/**
* 验证邮箱
*/
@Test
public void testCheckEmail() {
boolean result = RegexUtils.checkEmail("zha2_ngsan@sina.com.cn");
Assert.assertTrue(result);
}

/**
* 验证身份证号码
*/
@Test
public void testCheckIdCard() {
boolean result = RegexUtils.checkIdCard("432403193902273273");
Assert.assertTrue(result);
}

/**
* 验证手机号码
*/
@Test
public void testCheckMobile() {
boolean result = RegexUtils.checkMobile("+8613620285733");
Assert.assertTrue(result);
}

/**
* 验证电话号码
*/
@Test
public void testCheckPhone() {
boolean result = RegexUtils.checkPhone("+860738-4630706");
Assert.assertTrue(result);
}

/**
* 验证整数(正整数和负整数)
*/
@Test
public void testCheckDigit() {
boolean result = RegexUtils.checkDigit("123132");
Assert.assertTrue(result);
}

/**
* 验证小数和整数(正负整数和正负小数)
*/
@Test
public void testCheckDecimals() {
boolean result = RegexUtils.checkDecimals("-33.2");
Assert.assertTrue(result);
}

/**
* 验证空白字符
*/
@Test
public void testCheckBlankSpace() {
boolean result = RegexUtils.checkBlankSpace(" ");
Assert.assertTrue(result);
}

/**
* 匹配中文
*/
@Test
public void testCheckChinese() {
boolean result = RegexUtils.checkChinese("中文");
Assert.assertTrue(result);
}

/**
* 验证日期
*/
@Test
public void testCheckBirthday() {
boolean result = RegexUtils.checkBirthday("1992/09/03");
Assert.assertTrue(result);
}

/**
* 验证中国邮政编码
*/
@Test
public void testCheckPostcode() {
boolean result = RegexUtils.checkPostcode("41710