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()是会移动文件指针的位置,它会一个一个的匹配下去,指导结束!