Java正则表达式

时间:2022-07-25
本文章向大家介绍Java正则表达式,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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))),有四个这样的组:

  • ((A)(B(C)))
  • (A)
  • (B(C))
  • (C)

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

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

  • 捕获实例(if (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);
        
        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