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"+
"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);
System.out.println(regex);
while(m.find()){
//当在匹配中查找到相应的匹配时==一次查找,可以进行多次匹配操作
System.out.println("find() '"+m.group()+"' start="+m.start()+",end="+m.end());
if(m.lookingAt()){
System.out.println("lookingAt() '"+m.group()+"' start="+m.start()+",end="+m.end());
}
if(m.matches()){
System.out.println("matches() '"+m.matches()+"' start="+m.start()+",end="+m.matches());
}
}
}
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*ere","T\\w+","Never.*?!"}){
examine(element,secondElement);
}
}
}
}
死循环
input: As long as there is injustice,whenever a
find() 'there' start=11,end=16
find() 'there' start=11,end=16
find() 'there' start=11,end=16
find() 'there' start=11,end=16
find() 'there' start=11,end=16
......
------解决方案--------------------
你原先的写法没有问题,问题出在这里:
if(m.lookingAt()){
System.out.println("lookingAt() '"+m.group()+"' start="+m.start()+",end="+m.end());
}
if(m.matches()){
System.out.println("matches() '"+m.matches()+"' start="+m.start()+",end="+m.matches());
}
你把它注释掉看看
------解决方案--------------------
比如字符串实例:“As long as there is injustice,whenever a”
正则表达式:"\\w*ere\\w*"
执行:
while(m.find()){
//打印m.group();
if(m.lookingAt()){