62,630
社区成员




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());
}
你把它注释掉看看[/quote]
lookingAt() 尝试将从区域开头开始的输入序列与该模式匹配
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());
}
你把它注释掉看看
....
for(String secondElement:new String[]{"\\were\\w","\\were","T\\w+","Never.*?!"}){
examine(element,secondElement);
}
.....
input: As long as there is injustice,whenever a
\were\w
\were
find() 'here' start=12,end=16
T\w+
Never.*?!
input: baby cires out, wherever a distress
\were\w
find() 'herev' start=17,end=22
\were
find() 'here' start=17,end=21
T\w+
Never.*?!
input: signal sounds among the starts ... We all be there.
\were\w
\were
find() 'here' start=46,end=50
T\w+
Never.*?!
input: This fine ship, and this fine crew ...Never give up, Never surrender!
\were\w
\were
T\w+
find() 'This' start=0,end=4
lookingAt() 'This' start=0,end=4
Never.*?!
find() 'Never give up, Never surrender!' start=38,end=69