Java中有关正则表达式的包是java.util.regex
其中主要包含了这三个类Pattern、Matcher、PatternSyntaxException
其中
Pattern类:没有构造方法,需要调用其静态编译方法来创建他的对象,该方法可以接受正则表达式作为参数。
Matcher类:同样没有构造方法,需要调用Pattern的matcher方法来创建对象。
PatternSyntaxException类:是一个异常类,表示正则表达式模式中的语法错误。
附:常见正则表达式
匹配中文字符:
System.out.println(Pattern.matches("[\u4e00-\u9fa5]", “好”));
匹配Email地址
System.err.println(Pattern.matches("\w[-\w.+]*@([A-Za-z0-9][A-Za-z0-9]+\.)+[A-Za-z]{2,14}", “hello2020@qq.com”));
m-n 位的数字
System.out.println(Pattern.matches("^\d{1,3}$", “123”));
密码必须由字母和数字组成,且长度要在6-12位之间
System.out.println(Pattern.matches("^(?![0-9]+ ) ( ? ! [ a − z A − Z ] + )(?![a-zA-Z]+ )(?![a−zA−Z]+)[0-9A-Za-z]{6,12}$", “123hello456”));
一年的12个月(01~09和1~12) : ^(0?[1-9]|1[0-2])$
Pattern.matches("^((0?[1-9])|(1[0-2]))$", “11”)
匹配时分秒
System.out.println(Pattern.matches("([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]", “11:10:11”));
IP地址格式
System.out.println(Pattern.matches("((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}", “192.168.21.37”));
网址匹配包含http、https、ftp协议
System.out.println(Pattern.matches("^(https?|ftp)😕/[-a-zA-Z0-9+&@#/%?=_|!:,.;]*[-a-zA-Z0-9+&@#/%=_|]", “http://www.bdqn.cn/”));