2013-12-23 40 views
0

我的方法需要一個文件,並試圖提取報頭###Title###和關閉###---###之間的文本。我需要它提取多行並將每行放入數組中。但由於readAllLines()將所有行轉換爲數組,我不知道如何比較和匹配它。Java匹配器:如何匹配多個行與一個正則表達式

public static ArrayList<String> getData(File f, String title) throws IOException { 
    ArrayList<String> input = (ArrayList<String>) Files.readAllLines(f.toPath(), StandardCharsets.US_ASCII); 
    ArrayList<String> output = new ArrayList<String>(); 

    //String? readLines = somehow make it possible to match 
    System.out.println("Checking entry."); 

    Pattern p = Pattern.compile("###" + title + "###(.*)###---###", Pattern.DOTALL); 
    Matcher m = p.matcher(readLines); 
    if (m.matches()) { 
     m.matches(); 
     String matched = m.group(1); 
     System.out.println("Contents: " + matched); 
     String[] array = matched.split("\n"); 
     ArrayList<String> array2 = new ArrayList<String>(); 
     for (String j:array) { 
      array2.add(j); 
     } 
     output = array2; 
    } else { 
     System.out.println("No matches."); 
    } 
    return output; 
} 

這是我的文件,我100%確定編譯器正在讀取正確的文件。

###Test File### 
Entry 1 
Entry 2 
Data 1 
Data 2 
Test 1 
Test 2 
###---### 

輸出說「沒有匹配」。而不是條目。

+0

你的問題到底是什麼? –

+0

所有這些都是在一行還是在圖片中? – Keerthivasan

+0

@ PM77-1我如何讓它匹配而不是返回「不匹配」。方法? –

回答

4

你不需要這樣的正則表達式。這足以循環訪問數組,並逐行比較項目,將開始和結束標記之間的數據進行比較。

ArrayList<String> input = (ArrayList<String>) Files.readAllLines(f.toPath(), StandardCharsets.US_ASCII); 
ArrayList<String> output = new ArrayList<String>(); 

boolean matched = false; 
for (String line : input) { 
    if (line.equals("###---###") && matched) matched = false; //needed parentheses 
    if (matched) output.add(line); 
    if (line.equals("###Test File###") && !matched) matched = true; 
} 
+0

你的算法對我來說有點棘手,你能解釋一下嗎? – Keerthivasan

+1

現在,我可以理解它。當標題匹配時,添加下一行。當頁腳匹配時,您將匹配爲false。這將只添加它們之間的線。酷:)我有代表 – Keerthivasan

1

根據您的意見,如果他們要在相同的方式貼出來,然後我不認爲需要對這一要求regex。您可以逐行讀取並做了含有「###」的

public static void main(String args[]) 
    { 
    ArrayList<String> dataList = new ArrayList<String>(); 
    try{ 
    // Open the file that is the first 
    // command line parameter 
    FileInputStream fstream = new FileInputStream("textfile.txt"); 
    // Get the object of DataInputStream 
    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    String strLine; 
    //Read File Line By Line 
    while ((strLine = br.readLine()) != null) { 
    // this line will skip the header and footer with '###' 
    if(!strLine.contains("###"); 
    dataList.add(strLine); 
    } 
    //Close the input stream 
    in.close(); 
    }catch (Exception e){//Catch exception if any 
    System.err.println("Error: " + e.getMessage()); 
    } 
    } 
//Now dataList has all the data between ###Test File### and ###---### 
} 

您還可以更改包含根據您的要求忽略線方法參數

+0

這也將符合開始標記之前和結束標記之後的行。 – Szymon

+0

OP只是告訴,線路將如問題 – Keerthivasan

+0

所示。也許。但是這個問題的文本提出了更廣泛的用法。 – Szymon