2015-06-05 47 views
1

我正在試圖在簡單的" 30 "行中找到此形式的編號爲\s\d\d\s的行,並將其存儲在int變量中,但我沒有找到匹配項。我該如何解決它?在下一行中找到與正則表達式匹配的編號

簡單:

buildig 05:11 05:41 06:14 06:44 07:14 07:44 08:14 30 17:14 17:44 18:14 18:44 19:14 19:44 

代碼:

 Scanner scannerLines = new Scanner(file)) { 
    int lineNum = 0; 
    while (scannerLines.hasNextLine()) { 
     String line = scannerLines.nextLine(); 
     if (line.contains(" alle ")) { 
      String nextLine = scannerLines.nextLine(); 
      Pattern pattern = 
        Pattern.compile("\\s\\d\\d\\s"); 

      Matcher matcher = 
        pattern.matcher(nextLine);     
      System.out.println(matcher); 

     } 

    } 
+0

當你有** matcher **對象時,通過遍歷** matcher.find()**找到所有的出現。 – pnadczuk

回答

2

首先,你應該編譯外循環的行話。然後使用Matcher.find()獲取與您的正則表達式匹配的下一個組,並稍後修剪該組的值(由於「30」中的空格)。

Pattern pattern = Pattern.compile("\\s\\d\\d\\s"); 
int lineNum = 0; 

Scanner scannerLines = new Scanner(System.in); 
while (scannerLines.hasNextLine()) { 
    lineNum++; 
    while (scannerLines.hasNextLine()) { 
     String line = scannerLines.nextLine(); 
     Matcher matcher = pattern.matcher(line); 

     while (matcher.find()){ 
      int value = Integer.parseInt(matcher.group().trim()); 
      System.out.println("Found " + value + " at line " + lineNum); 
     } 
    } 
} 
0

你必須使用matcher.find()

Scanner scannerLines = new Scanner(file)) { 
    int lineNum = 0; 
    while (scannerLines.hasNextLine()) { 
     String line = scannerLines.nextLine(); 
     if (line.contains(" alle ")) { 
      String nextLine = scannerLines.nextLine(); 
      Pattern pattern = 
        Pattern.compile("\\s\\d\\d\\s"); 

      Matcher matcher = 
        pattern.matcher(nextLine); 

      while(matcher.find()){       
      System.out.println(matcher.group()); 
      } 

     } 

    }