轻松掌握java正则表达式使用

一、规则

正则表达式,按字面意思理解就是字符串匹配的规则表达式,匹配方式:从左向右匹配,如:定义一个字符串:String str = "abc";str.macthes("abc");// 返回true,意思是字符串str和规则表达式"abc"恰好能够匹配;str.macthes("cba");// 返回false,意思是字符串str和规则表达式"cba"不能匹配。至于规则表达式,可以按照如下规则进行组装:

字符 含义 java举例
^ 开头
$ 结尾
. 单个任意字符
* 前面任意个字符
? 0个或一个
+ 至少一个字符
\d 匹配数字 “19\d\d”,匹配1900-1999
\D 匹配非数字
\w 字母数字下划线
\W 非字母数字下划线
\s 空格,tab,制表符
\S 非空格、tab制表符
\u+十六进制 配置非as码 “a\u548cc”,匹配a和c
“abc” 精确匹配
() 用于分组
[] 匹配范围
[^] 不包含这个范围
表示个数范围 {2,3}或{2,}或
特殊字符 需要加\
| 或者

二、举例

分割字符串:String.split();
搜索字串:Matcher.find();
替换字符串:String.replaceAll();

1.字符串操作

精确匹配

  public static void main(String[] args) {
        String str="we are happy";
        //精确匹配we
        boolean we = str.matches("we");
        System.out.println(we);//输出false
    }

字符串拆分

 String str="we are happy";
 //按照指定字符拆分
 String[] strArr = str.split("\\s");
 System.out.println(Arrays.toString(strArr));//[we, are, happy]

字符串替换

String str="we are happy";
//按照规则进行替换 按匹配到的元素进行匹配
String strreplace = str.replaceAll("happy", "haha");
System.out.println(strreplace);//we are haha

2.使用类

String str="we are happy";
//定义正则表达式
String regex="happy";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
boolean matches = matcher.matches();
boolean isfind = matcher.find();
if(isfind){
	  matcher.start();//开始索引
	  matcher.end();//结束索引
}
//正则表达式匹配 匹配电话号码
Pattern pattern = Pattern.compile("^(\\d{3,4})\\-(\\d{6,8})$");
Matcher matcher = pattern.matcher("010-12345678");
if (matcher.matches()){
   String whole = matcher.group(0);
   String group1 = matcher.group(1);
   String group2 = matcher.group(2);
}
posted @ 2020-12-26 20:17  lecy6  阅读(93)  评论(0)    收藏  举报