2011-09-14 15 views
1

我要從發佈文本文件中的日期看起來像什麼開始,這只是它的4行,實際上文件是幾百行。來自文本文件的條形數據

週五,2011年9月9日
-STV 101 -------- 05:00 - 23:59 SSB 4185報告印製2011年9月8日在2:37

0-AH 104 -------- 07:00 - 23:00 AH GYM Report打印於2011年9月8日2:37

-BG 105 -------- 07:00 - 23 :00 SH GREAT HALL Report打印於2011年9月8日2:37

我想用這個文本文件做的事情是忽略第一行的日期,然後忽略' - '下一行,但在「STV 101」,「5:00」和「23:59」中讀取將它們保存爲vari然後忽略該行上的所有其他字符,然後在每行後忽略。

這是我目前正在閱讀的完全線條。然後,只要用戶將路徑放入scheduleTxt JTextfield中,我就調用此函數。它可以讀取和打印每一行很好。

public void readFile() throws IOException 
{ 
    try 
    { 
     FileInputStream fstream = new FileInputStream(scheduleTxt.getText()); 
     DataInputStream in = new DataInputStream(fstream); 
     BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
     String strLine; 

     while ((strLine = br.readLine()) != null) 
     { 
      System.out.println (strLine); 
     } 
     in.close(); 
    } 
    catch (Exception e){//Catch exception if any 
     System.err.println("Error: " + e.getMessage()); 
    } 
} 

UPDATE: it turns out I also need to strip Friday out of the top line and put it in a variable as well Thanks! Beef.

回答

3

Did not test it thoroughly, but this regular expression would capture the info you need in groups 2, 5 and 7: (Assuming you're only interested in "AH 104" in the example of "0-AH 104----") ^(\S)*-(([^-])*)(-)+((\S)+)\s-\s((\S)+)\s(.)*

String regex = "^(\\S)*-(([^-])*)(-)+((\\S)+)\\s-\\s((\\S)+)\\s(.)*"; 
    Pattern pattern = Pattern.compile(regex); 
    while ((strLine = br.readLine()) != null){ 
     Matcher matcher = pattern.matcher(strLine); 
     boolean matchFound = matcher.find(); 
     if (matchFound){ 
      String s1 = matcher.group(2); 
      String s2 = matcher.group(5); 
      String s3 = matcher.group(7); 
      System.out.println (s1 + " " + s2 + " " + s3); 
     } 

    } 

表達可能與非捕獲組,以捕捉只有你想要的信息來調整。

正則表達式的內容的說明:通過-結束

  1. ^(\S)*-匹配組的非空白字符。 注意:可能是^(.)*-而不是如果在第一個-之前有空白時不起作用。
  2. (([^-])*)匹配除-以外的每個字符組。
  3. (-)+匹配一組或多組-
  4. ((\S)+)匹配一個或多個非空白字符的組。這在第5組中被捕獲。
  5. \s-\s匹配一組空白,然後是-後跟空白。
  6. '((\ S)+)'與4.相同。在組7中被捕獲。
  7. \s(.)*匹配空格後跟任何內容,將被跳過。

有關正則表達式的更多信息,請參閱此tutorial。 還有幾個有用的cheatsheets左右。在設計/調試表達式時,regexp testing tool也可以證明非常有用。

+0

是的,在「0-AH 104 ----」的情況下,我只想要「AH 104」,謝謝,我會試試看看我得到了什麼! – Beef

+0

更新:效果很好,用更廣泛的文本文件版本測試過,並且沒有問題,再次感謝 – Beef

+0

我已經在答案上添加了關於表達式元素的解釋以供進一步參考 –