正则表达式
实际开发中,经常需要对字符串数据进行一些复杂的匹配、查找、替换等操作。通过”正则表达式“,可以方便的实现字符串的复杂操作.
正则表达式是一串特定字符,组成一个”规则字符串”,这个”规则字符串”是描述文本规则的工具。正则表达式就是记录文本规则的代码。
字符集合
[abc]a、b、c中任意一个字符
[^abc]除了a、b、c的任意字符
[a-z]a、b、c、、、、、、z中的任意一个字符
[a-zA-Z0-9]a~z、A~Z、0-9中任意一个字符
[a-z&&[^bc]]a-z中除了b和c以外的任意一个字符,其中&&表示”与”的关系
预定义字符集
. 任意一个字符
\d任意一个数字字符,相当于[0-9]
\w单词字符,相当于[a-zA-Z0-9_]
\s空白字符,相当于[\t\n\x0B\f\r]
\D 非数字字符
\W 非单词字符
\S 非空白字符
String regex1 = "[a-z]";
System.out.println("a".matches(regex1)); // true
String regex2 = "[^a-z]";
System.out.println("b".matches(regex2)); // false
String regex3 = "[a-z&&[^bc]]";
System.out.println("f".matches(regex3)); // true
System.out.println("b".matches(regex3)); // false
String regex4 = "\\d"; // [0-9]
System.out.println("1".matches(regex4)); // true
String regex5 = "\\D"; // [^0-9]
System.out.println("1".matches(regex5)); // false
String regex6 = "\\s"; // [\t\n\x0B\f\r]
System.out.println(" ".matches(regex6)); // true
String regex7 = "\\S"; // [^\s]
System.out.println(" ".matches(regex7)); // false
String regex8 = "\\w"; // [a-zA-Z_0-9]
System.out.println("_".matches(regex8)); // true
String regex9 = "\\W"; // [^\w]
System.out.println("_".matches(regex9)); // false
数量词
X? 表示0个或1个X
X* 表示0个或任意多个X
X+ 表示1个到任意多个X(大于等于1个X)
X{n}表示n个X
X{n,}表示n个到任意多个X(大于等于n个X)
X{n,m}表示n个到m个X
String regex10 = "[a-z]*";
String regex11 = "\\w+\\.jar";
String regex12 = "\\d?[a-z]?[a-z]*";
System.out.println("abcde".matches(regex10)); // true
System.out.println("".matches(regex10)); // true
System.out.println("lang.jar".matches(regex11));// true
System.out.println(".jar".matches(regex11)); // false
System.out.println("1abc".matches(regex12)); // true
System.out.println("abc".matches(regex12)); // true
String regex13 = "\\w{5}";
String regex14 = "\\d{5,}";
String regex15 = "[a-zA-Z]{5,8}";
System.out.println("abcef".matches(regex13)); // true
System.out.println("abcefg".matches(regex13)); // fasle
System.out.println("12345".matches(regex14)); // true
System.out.println("123456".matches(regex14)); // true
System.out.println("1234".matches(regex14)); // false
System.out.println("Hello".matches(regex15)); // true
System.out.println("HelloWorld".matches(regex15));// false
分组”()”
分组:()圆括号表示分组,可以将一系列正则表达式看做一个整体,分组时可以使用”|”表示”或”关系,例如:匹配手机号码前面的区号
(\+86|0086)?\s?\d{11}
上述例子中,圆括号表示这里需要出现”+86”或者”0086”
检索手机号码:+86 13838389438 (\+86)?\s*\d{11}
边界匹配
^代表字符串开始
$代表字符串结束
例如:匹配用户名规则---从头到尾连续8~10个单词字符
^\w{8,10}$
String正则API
// matches:将一个字符串与正则表达式进行匹配成功true,否则返回fasle
String emailRegEx = "^[a-zA-Z0-9_.-]+@([a-zA-Z0-9-]+\\.)+[a-zA-Z0-9]{2,4}$";
String email = "bilili@qq.com";
System.out.println(email.matches(emailRegEx));
// spilt方法,String的split方法可以将字符串按照特定的分隔符拆分成字符串数组。
String str = "java cpp php c# objective-c";
String[] strArr = str.split("\\s");
System.out.println(Arrays.toString(strArr));
// replaceAll方法 String提供了字符串替换的方法
String str1 = "abc123bcd45ef6g7890";
str1 = str1.replaceAll("\\d+", "数字");
System.out.println(str1);