正则表达式
- 由一些特定的字符组成,代表的是一个规则。
- 作用:校验数据格式是否合法。在一段文本中查找满足要求的内容。
public static void main(String[] args) {
// 1、字符类
System.out.println("a".matches("[abc]"));
System.out.println("e".matches("[abcd]"));
System.out.println("d".matches("[^abc]")); // [^abc] 不能是abc
System.out.println("a".matches("[^abc]")); // false
System.out.println("b".matches("[a-zA-Z]")); // a-z 或者 A-Z
System.out.println("1".matches("[a-zA-Z]"));
System.out.println("k".matches("[a-z&&[^bc]]")); // a到z,除了b和c
System.out.println("b".matches("[a-z&&[^bc]]"));
System.out.println("ab".matches("[a-zA-Z0-9]")); //false 注意:以上带[内容]的规则只能用于匹配单个字符串
// 1、预定义字符(只能匹配单个字符) . \d \D \s \S \w \W
System.out.println("徐".matches(".")); // .可以匹配任意字符
System.out.println("徐徐".matches("."));
System.out.println("1".matches("\\d")); // \\d表示一个数字字符
System.out.println("12".matches("\\d"));
System.out.println(" ".matches("\\s")); // \\s表示空格
System.out.println(" ".matches("\s\s"));
System.out.println("a".matches("\\S")); // \\S 表示非空格
System.out.println(" ".matches("\\S"));
System.out.println("a".matches("\\w")); // \w:[a-zA-Z_0-9]
System.out.println("_".matches("\\w"));
System.out.println("徐".matches("\\w"));
System.out.println("徐".matches("\\W"));
System.out.println("a".matches("\\W"));
System.out.println("-------------------");
// 3、数量词:? * + {n} {n, } {n,m}
System.out.println("a".matches("\\w?")); // ? 代表0次或者1次
System.out.println(" ".matches("\\w?"));
System.out.println("abc".matches("\\w?"));
System.out.println("abc12".matches("\\w*")); // * 代表0次或者多次
System.out.println("".matches("\\w*"));
System.out.println("abc12张".matches("\\w*"));
System.out.println("abc12".matches("\\w+")); // + 代表1次或者多次
System.out.println("".matches("\\w+"));
System.out.println("abc12啊".matches("\\w+"));
System.out.println("a3c".matches("\\w{3}")); // {3} 代表正好3次
System.out.println("abcd".matches("\\w{3}"));
System.out.println("abcd".matches("\\w{3,}")); // {3,} 代表>=3次
System.out.println("abc".matches("\\w{3,9}")); // {3,9} 代表大于等于3次,小于等于9次
// 4、其它的常用符号:(?i)忽略大小写、或:|,分组:()
System.out.println("abc".matches("(?i)abc"));
System.out.println("abc".matches("(?i)abc"));
System.out.println("abc".matches("a(?i)bc"));
System.out.println("Abc".matches("a((?i)b)c")); // false
System.out.println("123".matches("\\d{3}|[a-z]{3}"));
System.out.println("abc".matches("\\d{3}|[a-z]{3}"));
System.out.println("aAC".matches("\\d{3}|[a-z]{3}"));
// 必须是“我爱”开头,中间至少一个“编程”,最后至少一个“666”
System.out.println("我爱编程编程666".matches("我爱(编程)+(666)+"));
System.out.println("我爱编程编程6666666".matches("我爱(编程)+(666)+")); // false
}
规则小结