您的位置:程序门 -> java -> j2se / 基础类



问一个正规表达式中的matcher的问题


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


问一个正规表达式中的matcher的问题[已结贴,结贴人:javaglory]
发表于:2007-01-23 10:22:40 楼主
public   static   void   main(string   args[])
{
      system.out.println(getregexpvalbyidx( "[0-9]+ ", "%$^%11     12113$goodfdf678()) ",2));
}

public   static   string   getregexpvalbyidx(string   regexp,string   oristr,int   idx)
{            
pattern   p=pattern.compile(regexp);
matcher   matcher=p.matcher(oristr);
matcher.start(idx);
string   result=null;
if(matcher.find(idx))
      result=matcher.group();
return   result;
}

这个getregexpvalbyidx是想返回第idx个匹配的字符串,   无论idx参数设为什么,都只返回第一个匹配的的字符串.
发表于:2007-01-23 18:16:291楼 得分:0
blog   更新:
  think   in   java   各章后练习答案.....
  http://blog.csdn.net/heimaoxiaozi/
发表于:2007-01-23 19:40:072楼 得分:10
public   static   string   getregexpvalbyidx(string   regexp,   string   oristr,   int   idx)   {
        pattern   p   =   pattern.compile(regexp);
        matcher   matcher   =   p.matcher(oristr);
      //   matcher.start(idx);   在分组的模式下,此方法是返回以前匹配的匹配操作期间,由给定组所捕获的子序列的初始索引。
        string   result   =   null;
        for(int   i=0;matcher.find();i++){
            if(i==idx){
                result   =   matcher.group();
            }
        }
        return   result;
    }
发表于:2007-01-23 19:48:233楼 得分:0
javaglory   (我有准时结贴给分的好习惯)          
===================================
这个名字起得好
发表于:2007-01-23 21:03:004楼 得分:10
以下:
public   static   void   main(string   args[])
{
      system.out.println(getregexpvalbyidx( "[0-9]+ ", "%$^%11     12113$goodfdf678()) ",3));
}

public   static   string   getregexpvalbyidx(string   regexp,string   oristr,int   idx)
{            
        pattern   p=pattern.compile(regexp);
        matcher   matcher=p.matcher(oristr);

        string   result=null;
        int   index   =   1;
        while(matcher.find()){
                if(idx   ==   index){
                        result=matcher.group();
                        break;
                }
                index++;
        }
        return   result;
}
发表于:2007-01-25 09:41:475楼 得分:0
程序就可以运行了,但是不明白matcher.start(int   idx)的作用,

"在分组的模式下,此方法是返回以前匹配的匹配操作期间,由给定组所捕获的子序列的初始索引 "。

可能我语文差,理解不到这句的意思.


发表于:2007-01-26 00:21:326楼 得分:10
一个正则表达式,默认整个表达式算一个组,其余每对括号算一个组,每次匹配完之后,就会有若干个匹配组,start(int   idx)返回的是相应组的起始索引.比如一个正则表达式1(23)(45)存在3个组,整体是0组,(23)是1组,(45)是2组,对12345进行匹配,start(0)返回12345的起始索引0,start(1)返回23起始索引1,start(2)返回45索引3.


快速检索

最新资讯
热门点击