利用正则实现验证,代码可以最少化。
替换
public class Main {
public static void main(String[] args) {
String str = "fghkhjgkfjk648743fgd8gfg34374?,<$%^&*87";
String regex = "[^a-z]";
System.out.println(str.replaceAll(regex,""));
}
}
拆分
public class Main {
public static void main(String[] args) {
String str = "fghkd67hjgkfjk648743fgd833gfg34374?,<$%4343^&*87";
String regex = "\\d+";
String array [] = str.split(regex);
for(int i = 0; i < array.length; i ++){
System.out.println(array[i]);
}
}
}
判断
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String str = "12.678";
String regex = "\\d+(\\.\\d+)?"; // 判断整数或者小数
System.out.println("digital:" + str.matches(regex));
if(str.matches(regex)){
System.out.println(Double.parseDouble(str));
}
String str2 = "192.168.1.103";
String regex2 = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"; // 判断 ip 地址
System.out.println("ip:" + str2.matches(regex2));
String str3 = "2017-11-30";
String regex3 = "\\d{4}-\\d{2}-\\d{2}"; // 判断日期
Date date =new Date();
if(str3.matches(regex3)){
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
try{
date = simpleDateFormat.parse(str3);
}catch (Exception e){
e.printStackTrace();
}
System.out.println(date);
}
String str4 = "(0916)-4356110";
String str5 = "0916-4356110";
String str6 = "4356110";
String regex4 = "((\\(\\d{4}\\)-)|(\\d{4}-))?\\d{7}"; // 判断电话号码
System.out.println("number:" + str4.matches(regex4));
System.out.println("number:" + str5.matches(regex4));
System.out.println("number:" + str6.matches(regex4));
String str7 = "13122111623@sina.cn";
String str8 = "13122111623@sina.com";
String str9 = "972633408@qq.com";
String str10 = "yuzhen233@hotmail.com";
String str11 = "yuzhen233@gmail.com";
String str12 = "151340218@mail.dhu.edu.cn";
String str13 = "151340218@dhu.edu.cn";
String regex5 = "(\\d{11}@sina\\.(cn|com))" +
"|((\\d{5}|\\d{9}|\\d{10})@qq.com)" +
"|([a-zA-z]+\\d+@(hotmail|gmail).com)" +
"|(\\d{9}@((mail.dhu.edu.cn)|(dhu.edu.cn)))"; // 判断邮件地址
System.out.println("mailAdress:"+ str7.matches(regex5));
System.out.println("mailAdress:"+ str8.matches(regex5));
System.out.println("mailAdress:"+ str9.matches(regex5));
System.out.println("mailAdress:"+ str10.matches(regex5));
System.out.println("mailAdress:"+ str11.matches(regex5));
System.out.println("mailAdress:"+ str12.matches(regex5));
System.out.println("mailAdress:"+ str13.matches(regex5));
}
}