public static void main(String[] args) { System.out.println("a".matches("[abc]")); //true System.out.println("a".matches("[^abc]")); //false System.out.println("a".matches("[a-z]")); //true System.out.println("a".matches("[A-Z]")); //false System.out.println("0".matches("[0-9]")); //true System.out.println("a".matches("[a-ce-g]"));//true System.out.println("d".matches("[a-ce-g]"));//false System.out.println("5".matches("[a-ce-g0-5]"));//true System.out.println("a1d".matches("a[0-9]d")); //true 以a开头,以d结尾,中间一位数字 }
public static void main(String[] args) { System.out.println("abz".matches("a.z")); //true System.out.println("acz".matches("a.z")); //true System.out.println("a".matches("\\.")); //true System.out.println("1".matches("\\d")); //false System.out.println("1".matches("\\D")); //true System.out.println(" ".matches("\\s")); //false System.out.println("a".matches("\\S")); //true System.out.println("a".matches("\\w")); //true System.out.println("1".matches("\\w")); //true System.out.println("@".matches("\\w")); //false System.out.println("@".matches("\\W")); //true }
public static void main(String[] args) { System.out.println("a".matches("\\w?")); //true System.out.println("aa".matches("\\w*")); //true System.out.println("aa".matches("\\w+")); //true System.out.println("aa".matches("a{2}")); //true System.out.println("aaa".matches("a{2}")); //false System.out.println("a".matches("a{2}")); //false System.out.println("aaa".matches("a{2,}")); //true System.out.println("a".matches("a{2,3}")); //false System.out.println("aa".matches("a{2,3}")); //true //验证是否是手机号 // 1.第一位为1 // 2.第二位是3,5,8 3).后面9位都是数字 System.out.println("15812340987".matches("1[358]\\d{9}"));// true }
以小括号将相同规则进行分组
public static void main(String[] args) { String uuid = UUID.randomUUID().toString(); System.out.println(uuid); //0f030d0f-fa5f-44f3-a510-2cbe60b4c67f String str = "0f030d0f-fa5f-fa5f-44f3-a510-2cbe60b4c67f"; // 4-8位数字或者小写字母,以-结尾,并且出现4次,最后一次12位数字或者小写字母 System.out.println(uuid.matches("([a-z0-9]{4,8}-){4}([a-z0-9]{12})")); //true System.out.println(str.matches("([a-z0-9]{4,8}-){4}([a-z0-9]{12})")); //false }