Java正则表达式

2020-09-14  本文已影响0人  十毛tenmao

Java正则表达式时不时的用一下,虽然可以解决问题,总是没有完全弄明白其中的一些接口的含义。本文熟悉了相关的几个常见接口。

匹配

String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
Pattern.matches("hello world (\\d+)", content);
public class App {
    private static final Pattern PATTERN = Pattern.compile("hello world (\\d+)");
    public static void main(String[] args) {
        String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
        Matcher matcher = PATTERN.matcher(content);
        System.out.println(matcher.matches());
    }
}

捕获组

捕获组是通过从左至右计算其开括号来编号。例如,在表达式((A)(B(C))),有四个这样的组:

可以通过调用 matcher 对象的 groupCount 方法来查看表达式有多少个分组。groupCount 方法返回一个 int 值,表示matcher对象当前有多个捕获组。

还有一个特殊的组(group(0)),它总是代表整个表达式。该组不包括在 groupCount 的返回值中。

public class App {

    private static final Pattern PATTERN = Pattern.compile("hello (world (\\d+))");

    public static void main(String[] args) {
        String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
        Matcher matcher = PATTERN.matcher(content);
        
        if (matcher.find()) {
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println(matcher.group(i));
            }
        }
    }
}
hello world 1
world 1
1

匹配多个(while (matcher.find()))

public class App {

    private static final Pattern PATTERN = Pattern.compile("hello (world (\\d+))");

    public static void main(String[] args) {
        String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
        Matcher matcher = PATTERN.matcher(content);

        // 找到所有匹配字符串
        while (matcher.find()) {
            // 输出所有的匹配组
            for (int i = 0; i <= matcher.groupCount(); i++) {
                System.out.println(matcher.group(i));
            }
        }
    }
}
hello world 1
world 1
1
hello world 2
world 2
2
hello world 3
world 3
3
hello world 100
world 100
100

参考

上一篇 下一篇

猜你喜欢

热点阅读