Java正则表达式

420 阅读1分钟

一、正则表达式的常见规则:

1、单个字符:

①、[]型:

类型含义
[abc]只能是a或b或c
[^abc]除abc以外的所有小写英文字母
[a-zA-Z]a到z,A到Z
[a-d[m-p]]a-d 和 m-p
[a-z&&[def]]d或e或f (交集)
[a-z&&[^bc]]a-z除了bc
[a-z&&[^m-p]]a-z除了m-p

②、\型:

类型含义
.任何字符
\d0-9 (一个)
\D非数字(不能有数字)
\s一个空白字符
\S一个非空白字符
\w英文字母、数字、下划线
\W一个非 \w

注意:小写与大写相反!

例:

 1、只能出现 abc:
System.out.println("a".matches("[abc]"));   // true
System.out.println("d".matches("[abc]"));   // false

 2、不能出现 abc:
System.out.println("a".matches("[^abc]"));  // false
System.out.println("d".matches("[^abc]"));  // true

 3、 \d ——> 0-9 的数字(只能有一个)
System.out.println("5".matches("\d"));   // true
System.out.println("c".matches("\d"));   // false
System.out.println("33".matches("\d"));  // false

 4、 \w ——> 英文字母、数字、下划线:(只能有一个)
System.out.println("b".matches("\w"));   // true
System.out.println("_".matches("\w"));   // true
System.out.println("2".matches("\w"));   // true
System.out.println("22".matches("\w"));   // false
System.out.println("你".matches("\w"));   // false
System.out.println("你".matches("\W"));   // true

2、贪婪量词(多个):

类型含义
X?0或1次
X*0或多次
X+1或多次
X{n}正好n次
X{n,}至少n次
X{n,m}n-m次

例:

 1、数字、字母、下划线  至少6位:
System.out.println("3344ac_efe55".matches("\w{6,}"));  // true
System.out.println("4c_e".matches("\w{6,}"));  // false

 2、验证码:必须是数字和字符,4位 (无下划线)
System.out.println("45df".matches("[a-zA-Z0-9]{4}"));   // true
System.out.println("45_f".matches("[a-zA-Z0-9]{4}"));   // false
System.out.println("45df".matches("[\w&&[^_]]{4}"));   // true
System.out.println("45_f".matches("[\w&&[^_]]{4}"));   // false