java_正则表达式pattern类Matcher类_(字符串匹配)

本文深入探讨了Java中的Pattern类和Matcher类的使用,包括Pattern类的compile方法、Matcher类的matches、lookingAt和find方法,以及它们在字符串处理中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pattern类:
例子:
       

[java]  view plain copy
  1. Pattern pattern =Pattern.compile("[,\\s]+");  
  2.         String[] result = pattern.split("onetwo three,four,five, six");  
  3.         for(int i = 0; i<result.length; i++){  
  4.            System.out.println(result[i]);  
  5.         }  


输出结果是:
one
two
three
four
five
six
Pattern
类的静态方法compile用来编译正则表达式,在此[,\\s]+表示若干个","或者若干个空格匹配
split方法使用正则匹配将字符串切割成各子串并且返回

Matcher
类:
注意,Matcher的获得是通过Pattern.matcher(CharSequencecharSequence);输入必须是实现了CharSequence接口的类
常用方法:
matches()判断整个输入串是否匹配,整个匹配则返回true
例如下面会输出
true
        String str1 = "hello";
        Pattern pattern1 =Pattern.compile("hello");
        Matcher matcher1 =pattern1.matcher(str1);
        System.out.println(matcher1.matches());

lookingAt()从头开始寻找,找到匹配则返回
true
例如下面会输出
true
        String str2 = "hello yangfan!";
        Pattern pattern2 =Pattern.compile("hello");
        Matcher matcher2 =pattern2.matcher(str2);
        System.out.println(matcher2.lookingAt());

find()扫描输入串,寻找下一个匹配子串,存在则返回
true
例如下面将会将所有no替换成
yes
        Pattern pattern =Pattern.compile("no");
        Matcher matcher =pattern.matcher("Does jianyue love yangfan? no;" +
               "Does jianyue love yangfan? no;Does jianyue love yangfan? no;");
        StringBuffer sb = new StringBuffer();
        boolean find = matcher.find();
        while(find){
           matcher.appendReplacement(sb, "yes");
            find = matcher.find();
        }
        matcher.appendTail(sb);
        System.out.println(sb.toString());

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值