正则表达式

捕获组

捕获组是把多个字符当一个单独单元进行处理的方法,它通过对括号内的字符分组来创建。

例如,正则表达式 (dog) 创建了单一分组,组里包含"d",“o”,和"g"。

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

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

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

代码示例

  • 代码
public static void main(String[] args) {
    String content = "I am noob " + "from runoob.com.";
    String pattern = ".*runoob.*";

    // 创建 Pattern 对象
    Pattern r = Pattern.compile(pattern);
    // 现在创建 matcher 对象
    Matcher m = r.matcher(content);
    System.out.println("m.find()==" + m.find());
    System.out.println("m.groupCount()==" + m.groupCount());
    System.out.println("m.group()==" + m.group());
}

  • 返回结果
m.find()==true
m.groupCount()==0
m.group()==I am noob from runoob.com.
  • 代码
public static void main(String[] args) {
    // 按指定模式在字符串查找
    String line = "This order was placed for QT3000! OK?";
    // 正则表达式由3部分组,若查找成功,则会返回3个匹配子串
    String pattern = "(\\D*)(\\d+)(.*)";

    // 创建 Pattern 对象
    Pattern r = Pattern.compile(pattern);
    // 现在创建 matcher 对象
    Matcher m = r.matcher(line);
    if (m.find()) {
        // 分组数目
        int groupCount = m.groupCount();
        System.out.println("groupCount=" + groupCount);
        // m.group(0) 等同于 m.group()
        System.out.println("Found value: " + m.group(0));
        // group(int group) 返回在以前匹配操作期间由给定组捕获的输入子序列
        System.out.println("Found value: " + m.group(1));
        System.out.println("Found value: " + m.group(2));
        System.out.println("Found value: " + m.group(3));
    } else {
        System.out.println("NO MATCH");
    }
}
  • 返回结果
groupCount=3
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值