正则表达式 非捕获分组

来自姬鸿昌的知识库
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1Eq4y1E79W/?p=14

常用分组构造形式 说明
(?:pattern) 匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。

这对于用 "or"字符(|)组合模式部件的情况很有用。

例如,'industr(?:y|ies)' 是比 'industry|industries' 更经济的表达式。

(?=pattern) 它是一个非捕获匹配。

例如,'Windows (?=95|98|NT|2000)' 匹配 "Windows 2000" 中的 "Windows",

但不匹配 "Windows 3.1" 中的 "Windows"。

(?!pattern) 该表达式匹配不处于匹配 pattern 的字符串的起始点的搜索字符串。

它是一个非捕获匹配。例如,'Windows (?!95|98|NT|2000)' 匹配 "Windows 3.1" 中的 "Windows",但不匹配 "Windows 2000"中的 "Windows"

注意:使用非捕获分组就不能再通过 matcher.group() 获得子串

对比示例:在 "hello韩顺平教育 jack韩顺平老师 韩顺平同学hello" 中匹配 "韩顺平教育|韩顺平老师|韩顺平同学"

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExp08 {

    public static void main(String[] args) {

        String content = "hello韩顺平教育 jack韩顺平老师 韩顺平同学hello";

        String regStr = "韩顺平教育|韩顺平老师|韩顺平同学";

        Pattern pattern = Pattern.compile(regStr);

        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {

            System.out.println("找到:" + matcher.group(0));

        }

    }

}
找到:韩顺平教育
找到:韩顺平老师
找到:韩顺平同学



更经济的非捕获分组示例:在"hello韩顺平教育 jack韩顺平老师 韩顺平同学hello"中匹配"韩顺平(?:教育|老师|同学)"

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExp08 {

    public static void main(String[] args) {

        String content = "hello韩顺平教育 jack韩顺平老师 韩顺平同学hello";

        String regStr = "韩顺平(?:教育|老师|同学)";

        Pattern pattern = Pattern.compile(regStr);

        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {

            System.out.println("找到:" + matcher.group(0));

        }

    }

}
找到:韩顺平教育
找到:韩顺平老师
找到:韩顺平同学




示例:在"hello韩顺平教育 jack韩顺平老师 韩顺平同学hello"中匹配"韩顺平(?=教育|老师)"

要求:只匹配韩顺平教育和韩顺平老师的韩顺平,不匹配韩顺平同学的韩顺平

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExp08 {

    public static void main(String[] args) {

        String content = "hello韩顺平教育 jack韩顺平老师 韩顺平同学hello";

        String regStr = "韩顺平(?=教育|老师)";

        Pattern pattern = Pattern.compile(regStr);

        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {

            System.out.println("找到:" + matcher.group(0));

        }

    }

}
找到:韩顺平
找到:韩顺平



示例:在"hello韩顺平教育 jack韩顺平老师 韩顺平同学hello韩顺平学生"中匹配"韩顺平(?!教育|老师)"

要求:匹配 韩顺平教育和韩顺平老师之外的其他韩顺平

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExp08 {

    public static void main(String[] args) {

        String content = "hello韩顺平教育 jack韩顺平老师 韩顺平同学hello韩顺平学生";

        String regStr = "韩顺平(?!教育|老师)";

        Pattern pattern = Pattern.compile(regStr);

        Matcher matcher = pattern.matcher(content);

        while (matcher.find()) {

            System.out.println("找到:" + matcher.group(0));

        }

    }

}
找到:韩顺平
找到:韩顺平