https://www.cnblogs.com/jiafuwei/p/6080984.html
Java正则表达式--Matcher.group函数的用法
原来,group是针对()来说的,group(0)就是指的整个串,group(1) 指的是第一个括号里的东西,group(2)指的第二个括号里的东西。
最近学习正则表达式,发现Java中的一些术语与其他地方描述的有所差异。比如Java正则表达式中的“组”概念与《正则表达式必知必会》一书中讲述的“子表达式”其实是一样的,只是表述不同而已。由此也引发了使用JavaAPI时对group(int group)、start(int group)、end(int group)不是太理解。

package com.enation.newtest;
import java.io.*;
import java.util.regex.*;
import java.net.*;
public class MailTest{
public static void main(String[] args) throws Exception{
String regEx = "count(\\d+)(df)";
String s = "count000dfdfsdffaaaa1";
Pattern pat = Pattern.compile(regEx);
Matcher mat = pat.matcher(s);
if(mat.find()){
System.out.println(mat.group(2));
}
}
}

输出结果
mat.group() 输出为 count000df
mat.group(1) 输出为 000
mat.group(2) 输出为 df
如果没有括号会有异常。这就是() 的作用。 如何没有() 可以这样写:

public static void main(String []args){
String regEx = "count\\d+";
String s = "count000dfdfsdff1";
Pattern pat = Pattern.compile(regEx);
Matcher mat = pat.matcher(s);
if(mat.find()){
System.out.println(mat.group());
}
}
本文深入探讨了Java正则表达式的使用,重点讲解了Matcher类的group方法,通过实例展示了如何通过括号来捕获特定子串,适用于正则表达式初学者和技术人员。
5886

被折叠的 条评论
为什么被折叠?



