正则表达式之group()

来源:互联网 发布:sql语句添加数值 编辑:程序博客网 时间:2024/05/18 12:36

    java使用正则表达式我们都要使用group()来返回正则表达式中匹配的字符串。在创建Pattern对象后,在其中编译指定的表达式。然后调用Matcher方法在输入的字符串中匹配指定的表达式。使用group(),一定要先记得使用find()方法,否则就会出现编译错误。


测试程序:

public static void main(String[] args) {// TODO Auto-generated method stubPattern 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,3group(0) = ab1,3group(1) = b1,3group(2) = 1,3

     由上述的测试程序可以知道,group()和group(0)是等价的,都是匹配整个正则表达式的字符串。而group(1)是匹配第一个括号内的表达式返回的字符串。group(2)就是匹配第二个括号内的表达式返回的字符串。而在不知道顺序的情况下,正如问文中的测试程序一样,是按照表达式字符串的长度大小来输出返回的字符串。



0 0
原创粉丝点击