2013-12-23 41 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