java api1.6正则表达式说明:java.util.regex
1.java中用正则表达式判断字符串是否数字
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
String str="4566";
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
//str是数字返回true
System.out.println(isNum.matches());
//str不为数字返回false
str="fdsfds33";
isNum = pattern.matcher(str);
System.out.println(isNum.matches());
}
}
2..java正则验证IP地址
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
//正则ip通配符
String tph="\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
Pattern pattern = Pattern.compile(tph);
//str是错误IP返回true
String str="192.168.1.48";
Matcher isNum = pattern.matcher(str);
System.out.println(isNum.matches());
//str是错误IP返回false
str="127.400.600.2";
isNum = pattern.matcher(str);
System.out.println(isNum.matches());
}
}
3. java验证日期时间,解决润月:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
//正则日期通配符
String tph="^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
Pattern pattern = Pattern.compile(tph);
//java验证日期时间,解决润月
String str="2000-02-29 23:59:59";
Matcher isNum = pattern.matcher(str);
System.out.println(isNum.matches());
}
}
4.java验证邮箱格式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
//正则邮箱通配符
String tph="^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
Pattern pattern = Pattern.compile(tph);
//java验证邮箱格式
String str="a@aa.com";
Matcher isNum = pattern.matcher(str);
System.out.println(isNum.matches());
}
}
5.java验证手机号码
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String[] args) {
//正则手机号码通配符
String tph="^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
Pattern pattern = Pattern.compile(tph);
//java验证手机号码格式
String str="13693347897";
Matcher isNum = pattern.matcher(str);
System.out.println(isNum.matches());
}
}