一、正则表达式规则
预定义字符类
. 任何字符(与行结束符可能匹配也可能不匹配)
\d 数字:[0-9]
\D 非数字: [^0-9]
\s 空白字符:[ \t\n\x0B\f\r]
\S 非空白字符:[^\s]
\w 单词字符:[a-zA-Z_0-9]
\W 非单词字符:[^\w]
字符类
[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](并集)
[a-z&&[def]] d、e 或 f(交集)
[a-z&&[^bc]] a 到 z,除了 b 和 c:[ad-z](减去)
[a-z&&[^m-p]] a 到 z,而非 m 到 p:[a-lq-z](减去)
二、代码示例
1.字符匹配
public class Demo_regular {
public static void main(String[] args){
test1();
}
public static void test1(){
String regex1 = "[abc]"; //[]代表单个字符
String regex2 = "[^abc]";//^不是以abc开头的
String regex3 = "[a-zA-Z]";//范围
String regex4 = "[a-z[m-p]]"; //a-z或者m-p,取并集
System.out.println("a".matches(regex1));
System.out.println("a".matches(regex2));
System.out.println("B".matches(regex3));
System.out.println("n".matches(regex4));
}
}
输出:
2.正则的分割功能
public class Demo_regular {
public static void main(String[] args){
test2();
}
public static void test2(){
//正则表达式的分割功能
String s = "张三.李四.王五";
String[] arr = s.split("\\.");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
输出:
3.替换功能
public class Demo_regular {
public static void main(String[] args){
test3();
}
public static void test3(){
//替换功能
String s = "hello world";
String s2 = s.replace("hello","zhangsan");
System.out.println(s2);
//正则表达式替换功能
String s3 = "hello123world";
String regex = "\\d";
String s4 = s3.replaceAll(regex,"");
System.out.println(s4);
}
}
输出:
4.分组功能
public class Demo_regular {
public static void main(String[] args){
test4();
}
public static void test5(){
//正则表达式分组功能
String regex = "(.)\\1(.)\\2"; //\\1代表第一组又出现一次 \\2代表第二组又出现一次
System.out.println("快快乐乐".matches(regex));
String s2 = "我我.....要要...编编....程程";
String s3 = s2.replaceAll("\\.+","");
String s4 = s3.replaceAll("(.)\\1+","$1"); //$1代表第一组的内容
System.out.println(s4);
}
}
输出: