08.非捕获分组

非捕获分组

在这里插入图片描述

public class RegExp08 {
    public static void main(String[] args){
        String content = "魏红大佬,魏红董事长,魏红学长,魏红帅哥";
        //String resStr = "魏红(?:大佬|学长)";  //等价于非捕获分组 不能使用matcher.group(1)
        //找到 “魏红 ”关键字,但是只要求查找魏红董事长 和 魏红帅哥中含有的魏红     非捕获分组
        //String resStr = "魏红(?=董事长|帅哥)";
        //找到 “魏红 ”关键字,但是要求只是查找不是(魏红董事长 和 魏红帅哥)中含有的魏红  非捕获分组
        String resStr = "魏红(?!董事长|帅哥)";
        //1.构造模式对象Pattern
        Pattern pattern = Pattern.compile(resStr);
        //2.创造匹配器对象Matcher
        Matcher matcher =pattern.matcher(content);
        while (matcher.find()){
            System.out.println("找到:"+matcher.group(0));
        }

    }
}

程序结果:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41239465/article/details/121493900