2017-01-06 22 views
3

我有一個以下格式的文件,記錄由換行符分隔,但有些記錄中有換行符,如下所示。我需要獲取每條記錄並分別處理它們。該文件的大小可以是幾Mb。如何使用Java基於正則表達式將文件分解爲令牌

<?aaaaa> 
<?bbbb 
    bb> 
<?cccccc> 

我的代碼:

FileInputStream fs = new FileInputStream(FILE_PATH_NAME); 
Scanner scanner = new Scanner(fs); 
scanner.useDelimiter(Pattern.compile("<\\?")); 
if (scanner.hasNext()) { 
    String line = scanner.next(); 
    System.out.println(line); 
} 
scanner.close(); 

但我有開始時< \結果呢?刪除:

aaaaa> 
bbbb 
    bb> 
cccccc> 

我知道掃描儀消耗任何匹配分隔符模式的輸入。我所能想到的是將分隔符模式重新添加到每條記錄中。

有沒有一種方法可以不刪除定界模式?

回答

5

歇只有當由">"字符前面有一個換行符:

scanner.useDelimiter("(?<=>)\\R"); // Note you can pass a string directly 

\R是獨立於系統的換行符
(?<=>)看後面斷言(不消耗)的前一個字符是>

加上它很酷,因爲<=>看起來像Darth Vader's TIE fighter

+0

(笑)所以它! – DevilsHnd

+0

我測試過它,它工作!非常感謝! – jlp

+0

我測試了更多的記錄,這種方法在同一行上做了一些記錄。你能幫忙嗎? – jlp

1

我假設你想在任何地方忽略換行符'\n'

我會讀whole file into a String,然後remove all of the '\n's in the String。這個問題的代碼部分是這樣的:

String fileString = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8); 
fileString = fileString.replace("\n", ""); 
Scanner scanner = new Scanner(fileString); 
... //your code 

隨意問你可能有任何進一步的問題!

+0

該文件可能是幾MB大,不知道如果將整個文件存儲到字符串中是否會導致任何問題。 – jlp

+0

@jlp我不擔心文件的大小是幾兆字節,但你說得對,這種方法不能很好地擴展。 –

0

這是通過使用StringBuilder做的一種方式:

public static void main(String[] args) throws FileNotFoundException { 
    Scanner in = new Scanner(new File("C:\\test.txt")); 
    StringBuilder builder = new StringBuilder(); 

    String input = null; 
    while (in.hasNextLine() && null != (input = in.nextLine())) { 
     for (int x = 0; x < input.length(); x++) { 
      builder.append(input.charAt(x)); 
      if (input.charAt(x) == '>') { 
       System.out.println(builder.toString()); 
       builder = new StringBuilder(); 
      } 
     } 
    } 

    in.close(); 
} 

輸入:

<?aaaaa> 
<?bbbb 
    bb> 
<?cccccc> 

輸出:

<?aaaaa> 
<?bbbb  bb> 
<?cccccc> 
相關問題