Java 中正则表达式的使用

178 阅读3分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第22天,点击查看活动详情

最近在工作中遇到一些要读取s3 上的文件的事情,s3 上的文件命名是按照日期及时间进行partition 的,所以在构造这个文件名的时候,就要用到正则表达式。关于正则表达式的语法这里就不做过多的叙述了,下面就简单介绍一下Java 中正则表达式的使用,以便更好更快速地支持开发。

Pattern 和Matcher

正则表达式相关的,最常用的,是放在在java.util.regex 包下面的。有两个类,分别是Pattern 和Matcher。

Pattern 是一个用来描述正则表达式的模式;

Matcher 用来表示某个Pattern 实例与某个字符串的匹配结果,或者说用来描述匹配信息,匹配程度等等,然后返回匹配的“衡量标准”。(通过调用Matcher 类提供的方法来实现)

Pattern 类的构造函数被定义成了私有的,正常使用过程中,一般是通过Pattern.compile() 静态方法来生成一个Pattern 对象。compile 方法中传入我们待匹配的正则表达式。

而Matcher 类的对象则是由Pattern 对象的matcher(CharSequence input) 方法获得的。参数传入待匹配的字符串。

常用方法和场景

Matcher 类的match 方法

  • public boolean matches()

确认是否和正则表达式匹配,代码示例:

public static void main(String args[]) throws Exception {
  String str1 = "s3://category/231/20220222-111111/";
  Pattern pattern = Pattern.compile("^s3?://.*/$");
  Matcher matcher = pattern.matcher(str1);
  System.out.println(matcher.matches());
}

输出结果为false。

首先是生成一个Pattern 对象,然后调用matcher 方法,生成一个Matcher 的对象,最后可以由Matcher 的matches 方法判断是否匹配。

Matcher 类的find 方法

  • public boolean find()

上面那个方法是判断整个字符串是否可以完全匹配的,只有在整个字符串全部匹配成功后,match 方法才会返回true。但是有些场景我们想要匹配某个字符串的一部分,那么就需要使用Matcher 的find 方法了,代码示例:

public static void main(String[] args) {
  String string = "test first;test second;test third;";
  Pattern pattern = Pattern.compile("test\s(?<separator>\w+?);");
  Matcher matcher = pattern.matcher(string);
  while (matcher.find()) {
    int start = matcher.start();
    int end = matcher.end();
    String content = matcher.group(0);
    String result = String.format("the string from %s to %s, content is: %s", start, end, content);
    System.out.println(result);
  }
}

返回结果为:

the string from 0 to 11, content is: test first;
the string from 11 to 23, content is: test second;
the string from 23 to 34, content is: test third;

这个例子也比较好理解,从代码及返回结果,直观上我们就可以看出:

find 方法用来匹配字符串中的某个部分。如果匹配成功,那么Matcher 实例就会记录这次匹配的位置,同时返回true。当之后再调用find 方法,会从上次匹配过的位置的后面继续匹配,以此重复。

所以可以多次调用find 方法,直到返回false 结束。

总结

以上两个方法就是我们日常开发中最常用到的两个方法,熟记这些内容,可以应对我们开发工作中80% 的场景。