java.lang.IllegalStateException: No match found 的分析解决

用java写正则表达式,按照网上的例子来,发现有错误,即使是很简单的匹配也出错
java.lang.IllegalStateException: No match found
后来查了下明白了。

 
  
import java.util.regex.*;
public class test_rex {


	public static void main(String[] args) throws Exception{
		// TODO Auto-generated method stub
		String text = "Kelvin Li and Kelvin Chan are both working in Kelvin Chen's KelvinSoftShop company";
		String reg = "Kevin";
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(text);
		System.out.println(matcher.group());
		//上部分
		//////////////////////////////////////////////////
		//下部分
			Pattern p = Pattern.compile("ca+t");  
			Matcher m = p.matcher("one cat,two caats in the yard, caaats"); 
			while(m.find()){
			System.out.println(m.group());
			}
			
			//System.out.println("该次查找获得匹配组的数量为:"+m.groupCount());
		
	}


}

上面的代码,分两部分,第一部分是错误的形式,第二部分是正确的,需要先执行find函数才能找到。在java api文档中,明确写出:

 group

public String group(int group)
返回在 以前匹配操作期间由给定组捕获的输入子序列。
所以要现有匹配动作,即find()函数。正确的形式:

while( m.find() ){
	System.out.println(m.group());
}

而groupCount是捕获组的数量。注意!!捕获组是正则表达式语法中的概念,一个()为一个捕获组。(ca)(t)这时两个捕获组,有的捕获组还能命名,这个在jdk1.7中已经支持了。(cat)的捕获组是1,cat的捕获组是0,代表整个式子是单独的正则表达式。而相关的group(n)是指单独匹配第n个捕获组的捕获结果。对于(ca)(t),group(2)就是说匹配的t。这里要注意啊,不是匹配结果的数量。


你可能感兴趣的:(java)