2011-04-11 62 views
1

在閱讀Pattern的文檔時,它將\s聲明爲空白字符:[ \t\n\x0B\f\r]。那麼爲什麼下面的第二臺掃描儀會返回null,我怎樣才能使這個模式與新的行字符一起工作?Java模式新行問題

import java.util.*; 

public class Main 
{ 
    public static void main(String[] args) 
    { 

     String pattern = "\\s*a"; 

     Scanner scanner1 = new Scanner(" \t a"); 
     Scanner scanner2 = new Scanner(" \t\n a"); 

     System.out.println(scanner1.findInLine(pattern)); 
     System.out.println(scanner2.findInLine(pattern)); 
    } 
} 

輸出:

  a 
null 

回答

7

findInLine停止當它遇到一個換行符(顧名思義):

" \t\n a" 
^^^^ 
    | 
    +-- this is where findInLine(...) searches for the pattern: `\s*a` 

您應該使用findWithinHorizon(...)代替:

String pattern = "\\s*a"; 
Scanner scanner1 = new Scanner(" \t a"); 
Scanner scanner2 = new Scanner(" \t\n a"); 
System.out.printf(">%s<\n\n", scanner1.findInLine(pattern)); 
System.out.printf(">%s<", scanner2.findWithinHorizon(pattern, 0)); 

將會打印:

>  a< 

> 
a< 
+0

當然你是對的。我不能相信我錯過了這一點。謝謝。 – LandonSchropp 2011-04-11 08:04:35

+0

:)不客氣。 – 2011-04-11 08:05:33