Matche类在正则表达式中的应用 -- 《JAVA编程思想》41

Matcher 类是基于正则表达式构造的对象,今天一起来看看 Matcher 类的在正则表达式中的应用。

static Pattern.complie(String regex ) 方法编译正则表达式后生成 Pattern 类,在通过 Pattern 对象的 matcher(CharSequence input) 方法指定需匹配的字符串后生成 Matcher 对象(CharSequence 为字符序列接口,String 、StringBuffer、StringBuilder 均实现了此接口)。

  Matcher m = Pattern.compile("[a-z][0-9]").matcher("a1 b2 c3");

接下来,依次来看看 Matcher 类中的各种常用方法:

(1) boolean matches()

matches() 用于判断整个字符串是否满足正则表达式

        Matcher m = Pattern.compile("[a-z]+[0-9]+").matcher("abc123");
        System.out.println(m.matches());
true

(2) boolean lookingAt()

lookingAt() 用于判断字符串开头部分是否满足正则表达式

        Matcher m = Pattern.compile("[a-z]+[0-9]+").matcher("abc123 def");
        System.out.println(m.lookingAt());
true

(3)String group()

返回前一次匹配操作第0组的字符

这里顺带解释**组(Groups)**的概念:组是用括号划分的正则表达式,可以根据组的编号来引用某个组,组号0代表整个正则表达式。

示例:

A(B(C))D

上述例子中表示3个组:组0是ABCD,组1是BC,组2C,它们通过 () 划分,整个表达式代表组0。

(4)String group(int i )

返回前一次匹配操作(如:m.find() )指定组匹配的字符,有则返回,无则返回 null。

(5)int groupCount()

返回匹配上的分组数目

关于组的概念初看会有点懵,通过下面这个例子来加深理解:

public class Groups {

    public static final String POEM = "Twas brillig, and the slithy toves\n" +
            "Did gyre and gimble in the wabe.\n" +
            "All mimsy were the borogoves,\n" +
            "And the mome raths outgrabe.\n\n" +
            "Beware the Jabberwock,my son,\n" +
            "The jaws that bite, the claws that catch.\n" +
            "The frumious Bandersnatch";

    public static void main(String[] args) {
        Matcher m = Pattern.compile("(?m)(\\S+)\\s+((\\S+)\\s+(\\S+))$").matcher(POEM);
        while (m.find()) {
            for (int i = 0; i <= m.groupCount(); i++) {
                System.out.print("[" + m.group(i) + "]");
            }
            System.out.println();
        }
    }
    
}

(?m)表示开启匹配多行模式,每次匹配一行,具体介绍可以参照Pattern的多种匹配模式中 Pattern 匹配模式的部分。

上例中的正则表达式(s+表示匹配空格字符,S+表示匹配非空格字符)可以分为5组:

第0组

(\S+)\s+((\S+)\s+(\S+)) 匹配非空格字符开头,中间有空格字符,再接非空格字符、空格字符,最后以非空格字符结尾。

简单来说解释匹配每行最后三个词组,它们首尾不包含空格,每个词组中间用空格分隔开。

第1组

(\S+)

匹配第一个词组

第2组

((\S+)\s+(\S+))

匹配第二个词组和第三个词组,中间必须带有空格

第3组

(\S+)

匹配第二个词组

第4组

(\S+)

匹配第三个词组

故最终打印结果如下所示

[the slithy toves][the][slithy toves][slithy][toves]
[in the wabe.][in][the wabe.][the][wabe.]
[were the borogoves,][were][the borogoves,][the][borogoves,]
[mome raths outgrabe.][mome][raths outgrabe.][raths][outgrabe.]
[the Jabberwock,my son,][the][Jabberwock,my son,][Jabberwock,my][son,]
[claws that catch.][claws][that catch.][that][catch.]
[The frumious Bandersnatch][The][frumious Bandersnatch][frumious][Bandersnatch]

(6) boolean find()

find() 用于在 CharSequence 中依次向后查找多个满足正则表达式的对象,有则返回 true ,无则返回 false 。

        Matcher m = Pattern.compile("[a-z]+").matcher("abc def ghi");
        while (m.find()) {
            System.out.println(m.group());
        }
abc
def
ghi

(7) boolean find(int start)

find() 指定字符串下标 start 为起点在 CharSequence 中查找满足正则表达式的字符,有则返回 true ,无则返回 false 。

        Matcher m = Pattern.compile("\\S+").matcher("how are you");
        int i = 0;
        while (m.find(i)) {
            System.out.println(m.group() + " ");
            i++;
        }
how 
ow 
w 
are 
are 
re 
e 
you 
you 
ou 
u 

(8) int start(int group)

返回前一次匹配操作的起始索引

        Matcher m = Pattern.compile("[a-z]+").matcher("abc def ghi");
        while (m.find()) {
            System.out.print(m.group()+" startIndex:"+m.start());
            System.out.println();
        }
abc startIndex:0
def startIndex:4
ghi startIndex:8

(9) int end(int group)

返回前一次匹配操作的结束索引+1

        Matcher m = Pattern.compile("[a-z]+").matcher("abc def ghi");
        while (m.find()) {
            System.out.print(m.group() + " endIndex:" + m.end());
            System.out.println();
        }
abc endIndex:3
def endIndex:7
ghi endIndex:11

(10) reset(String str)

将 Matcher 对象重新设置到字符串起始位置进行匹配,使用 reset() 进行重置比通过 new 生成新的 Matcher 对象可以减少开销。

public class Resetting {

    public static void main(String[] args) {
        Matcher m = Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");
        while (m.find()) {
            System.out.print(m.group() + " ");
        }
        System.out.println();
        m.reset();
        while (m.find()) {
            System.out.print (m.group() + " ");
        }
    }

}
fix rug bag 
fix rug bag

(11) reset(String str)

将 Matcher 对象重新设置到新的字符串进行匹配

public class Resetting {

    public static void main(String[] args) {
        Matcher m = Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");
        while (m.find()) {
            System.out.print(m.group() + " ");
        }
        System.out.println();
        m.reset("fix the rig with rags");
        while (m.find()) {
            System.out.print (m.group() + " ");
        }
    }

}
fix rug bag 
fix rig rag 

本次分享至此结束,希望本文对你有所帮助,若能点亮下方的点赞按钮,在下感激不尽,谢谢您的【精神支持】。

若有任何疑问,也欢迎与我交流,若存在不足之处,也欢迎各位指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BaymaxCS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值