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

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

 
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() ){
<span style="white-space:pre">	</span>System.out.println(m.group());
}

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


  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值