如題。對於java正則表達式這幾個方法匹配一次后的,匹配位置搞不太清楚,就寫了幾個樣例。例如以下:
String ss="ooaaoo";
Pattern pt=Pattern.compile("(o+)");
Matcher mt=pt.matcher(ss);
// mt.lookingAt();
// mt.matches();
while(mt.find()){
System.out.println(mt.group(1)+"|||"+mt.start());
}
這個結果非常明顯會匹配二次,一次在0位置,一次在4位置。
看以下的代碼
String ss="ooaaoo";
Pattern pt=Pattern.compile("(o+)");
Matcher mt=pt.matcher(ss);
mt.lookingAt();
// mt.matches();
while(mt.find()){
System.out.println(mt.group(1)+"|||"+mt.start());
}當我們把matches或lookingat方法之中的一個的凝視拿掉之后,僅僅會發生一次匹配,就是在4位置。
再看以下的代碼:
String ss="aaooaaoo";
Pattern pt=Pattern.compile("(o+)");
Matcher mt=pt.matcher(ss);
mt.lookingAt();
// mt.matches();
while(mt.find()){
System.out.println(mt.group(1)+"|||"+mt.start());
}我們的輸入字符串ss發生了變化。
這個程序結果會發生二次匹配,一次在2位置,一次在4位置。
所以可得出下面結論:
1.當我們的輸入字符串ss開頭不匹配正則表達式的時候,matches和lookingat都不影響下次匹配位置。
2.假設輸入字符串開頭匹配正則表達式。調用matches或lookingat之后。下一次匹配的位置。會在去掉開頭匹配的字符串之后。
