import java.util.regex.*;
import static net.mindview.util.Print.*;public class P303EX12 {
static public final String POEM = "Twas brillig, and the slithy toves\n"
+ "Did gyre and gimble in the wabe.\n"
+ "All mimsy were the borogoves,\n"
+ "And the mome raths outgrabe.\n\n"
+ "Beware the Jabberwock, my son,\n"
+ "The jaws that bite, the claws that catch.\n"
+ "Beware the Jubjub bird, and shun\n"
+ "The frumious Bandersnatch."; public static void main(String[] args) {
int count = 0;
Matcher m = Pattern.compile("(^[^A-Z]|\\s+[^A-Z])\\w+").matcher(POEM);
// Matcher m = Pattern.compile("(^[a-z]|\\s+[a-z])\\w+").matcher(POEM);
while (m.find()) {
for (int j = 0; j <= m.groupCount(); j++) {
printnb(m.group(j));
}
count++;
}
print();
print(count);
}
}
代码如上,Thinking in Java第四版第13章第12题。使用第一个m的时候,会多出一个Beware,这个结果应该是不匹配的,求助为什么\n\n就会出错,\s+应该是多个空白字符才对啊

解决方案 »

  1.   

    Matcher m = Pattern.compile("(^[^A-Z]|\\s+[^A-Z|\\s])\\w+").matcher(POEM);
      

  2.   

    感谢,明白了,^[^A-Z]\\s+是一个表达式,匹配了第一个换行符后又去判断下一个换行符是不是非A-Z开始的,结果确实是非A-Z的,也是一个单词,所以打印了
      

  3.   

    跟空格没关系,主要是因为正则默认情况下是单行模式。\n刚好是换行,所以[^A-Z]可以匹配换行,而[a-z]匹配不到换行,其实\n\n和Beware他们是一组打印的。你可以在每一个group后加上一个符号就好知道了。比如
    printnb(m.group(j)+"##");