正则表达式基本概念

来源:互联网 发布:知乎马前卒是谁 编辑:程序博客网 时间:2024/06/05 02:36


正则表达式: 正确的规则

 专门用于对字符串的操作
规则是有符号组成的,用操作字符串变得简单
弊端:阅读性降低了
 所以学习正则其实就是学习符号的使用

1,匹配:
 String 类中提供了匹配boolean matches 的方法
 
  String tel = "15800022004411";
  String regex = "1[358]\\d{9}";
  boolean b = tel.matches(regex);

2,切割

String temp = "zhang  lis  wu";
 String regex=" +";
String temp = "zhangsan.lisi.wangwu";
  String regex = "\\.";
 
 String temp = "qwe##sds&&&&ddsSSad";
 String regex="(.)\\1+"; // 为了实现规则的复用,用()将需要复用的规则封装
                就称为了正则表达式中的组,每一个组都有编号,从1开始
                通过使用编号就可以复用对应组的规则内容,注意,编号必须用到组的后面
                也就是说:先封装再调用

3,替换:

String temp = "159000001111";
temp = temp .replaceAll("(
\\d){3}\\d{4}(\\d)(4)","$1*****$2");
      // $ 可以在多参数时,后面的参数可以通过$编号的形式取到前一个参数的组

4,获取
 
   实现获取:将符合规则内容取出来
用到正则表达式对象, java.util.regex.Pattern

1,将字符串规则封装成Pattern对象,compile(regex)
2,通过正则表达式对象获取匹配器对象,用对将正则规则作用到要操作的字符串上
 3,通过匹配器对象的方法,对字符串进行操作
 Pattern p =Pattern.compile("a+b");//将规则编译成对象
Mother m = p.matcher("aaaaab");//和要操作的字符串关联,生成匹配器对象
boolean b = m.matches();// 使用匹配对象方法对字符串操作

String temp = "da jia zhu yi ming tian fang jia";
String regex = "
\\b[a-zA-Z]{3}\\b";
Pattern p = Pattern.compile(regex);
Matcher m =p.matcher(temp);

while(m.find()){ 
 System.out.println(m.group());
 }

0 0
原创粉丝点击