Matcher匹配器中的方法!

package Chapter13_String;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StartEnd {
	public static String str=
			"As long as there is injustice,whenever a\n"+
			"Targathian baby cires out, wherever a distress\n"+
			"signal sounds among the starts ... We all be there.\n"+
			"This fine ship, and this fine crew ..."+
			"Never give up, Never surrender!";
	public static void examine(String s,String regex){
		Pattern p=Pattern.compile(regex);
		Matcher m=p.matcher(s);
		while(m.find()){
			System.out.println(regex);
			System.out.println("find() '"+m.group()+"' start="+m.start()+",end="+m.end());
			if(m.matches()){
				System.out.println("matches() '"+m.matches()+"' start="+m.start()+",end="+m.matches());
			}
			if(m.lookingAt()){
				System.out.println("lookingAt() '"+m.group()+"' start="+m.start()+",end="+m.end());
			}
			break;//~~~~~~~~~~~~~~~~`
		}
	}
	public static void main(String[] args){
		for(String element:str.split("\n")){
			System.out.println("input: "+element);
			for(String secondElement:new String[]{"\\w*ere\\w*","\\w*ever","T\\w+","Never.*?!"}){
				examine(element,secondElement);
			}
		}
		Pattern p=Pattern.compile("as\\w");
		Matcher m=p.matcher("asdasd");
		//~~~~~~~~~~~~~~~~~
		while(m.find()){
			System.out.println(m.group());
		}
	}
	
}

这个纠结了半天,稍微改了下书上的代码,就成了死循环了,测了一下午,注意那两行的注释!

发现匹配器对象中的lookingAt()和matches()的方法每次都重置文件指针到0的位置,而find()是会移动文件指针的位置,它会一个一个的匹配下去,指导结束!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值