前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java正则表达式

Java正则表达式

作者头像
十毛
发布2020-09-17 17:14:33
6230
发布2020-09-17 17:14:33
举报
文章被收录于专栏:用户1337634的专栏

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

匹配

  • 直接匹配
代码语言:javascript
复制
String content = "hello world 1, hello world 2, hello world 3, hello world 100.";
Pattern.matches("hello world (\\d+)", content);
  • 预编译
代码语言:javascript
复制
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()))
代码语言:javascript
复制
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));
            }
        }
    }
}
  • 输出
代码语言:javascript
复制
hello world 1
world 1
1

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

代码语言:javascript
复制
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));
            }
        }
    }
}
  • 输出
代码语言:javascript
复制
hello world 1
world 1
1
hello world 2
world 2
2
hello world 3
world 3
3
hello world 100
world 100
100
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 匹配
  • 捕获组
  • 匹配多个(while (matcher.find()))
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档