正则表达式之group()
发布时间:2020-12-14 01:01:05 所属栏目:百科 来源:网络整理
导读:java使用正则表达式我们都要使用group()来返回正则表达式中匹配的字符串。在创建Pattern对象后,在其中编译指定的表达式。然后调用Matcher方法在输入的字符串中匹配指定的表达式。使用group(),一定要先记得使用find()方法,否则就会出现编译错误。 测试程序
java使用正则表达式我们都要使用group()来返回正则表达式中匹配的字符串。在创建Pattern对象后,在其中编译指定的表达式。然后调用Matcher方法在输入的字符串中匹配指定的表达式。使用group(),一定要先记得使用find()方法,否则就会出现编译错误。
测试程序:
public static void main(String[] args) { // TODO Auto-generated method stub Pattern pa = Pattern.compile("[a]([b-c](d+,d+))"); String str = "ab1,3"; Matcher ma = pa.matcher(str); if(ma.find()) { System.out.println("group() = "+ma.group()); System.out.println("group(0) = "+ma.group(0)); System.out.println("group(1) = "+ma.group(1)); System.out.println("group(2) = "+ma.group(2)); System.out.println(); } //System.out.println("m.groupCount() ="+ma.groupCount()); }输出:
group() = ab1,3 group(0) = ab1,3 group(1) = b1,3 group(2) = 1,3 由上述的测试程序可以知道,group()和group(0)是等价的,都是匹配整个正则表达式的字符串。而group(1)是匹配第一个括号内的表达式返回的字符串。group(2)就是匹配第二个括号内的表达式返回的字符串。而在不知道顺序的情况下,正如问文中的测试程序一样,是按照表达式字符串的长度大小来输出返回的字符串。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |