簡體   English   中英

如何在Java中搜索多行並行文本?

[英]How to search for multiline-parallel text in Java?

考慮一個文本文件中帶有以下標題的表

    Table name goes here
                                                                     Page 1
    This is column one                 This is   This
                         This is       column    is column
                         column two f   thre f    three f
                                                 and hal f

     Row1 in column 1    Row2InCol2     Row3       Row4InCol4


                                                                     Page 2


 This is column one                   This is     This
                        This is       column    is column
                        column two f   thre f    three f
                                                and hal f


 Grand Total: -       12               13        25     

我想搜索“這是三列f和hal f列”列,這樣一來,當我找到此文本時,就能夠獲得此列開始的String索引位置(“ This”的索引)和此列結束的索引位置(單詞“ hal f”結束的索引,即“ f”的索引)。 請注意,所有列均包含單詞“ This”和字母“ f”,並且我應該能夠以與上述類似的方式搜索任何列的開始索引和結束索引。

我希望能夠執行此操作,因為我想實現一個解析器,該解析器可以解析文本文件中的表,在該文本文件中,列標題和列數據的索引位置從一頁到另一頁不一致(其中,換頁符表示末尾)頁)

我不是在尋找任何這樣的算法。 我想知道Pattern和Matcher類(或任何其他API)是否支持如上所述的多行文本搜索嗎?

過去對我有用的簡單模式。

// split on two ore more spaces.
String[] fields = line.split("\\s{2,}");

這會將一個空間視為字段的一部分。

因為您要搜索的文本是固定的文字,所以正則表達式不是首選的武器-只需在整個文本(包括換行符String.indexOf(String)使用String.indexOf(String) ,從第一個"This"到最后一個"f"

String target = "This\nThis is       column    is column\n                        column two f   thre f    three f\n                                                and hal f";

int start = input.indexOf(target);
int end = start + target.length();

若要查找下一個匹配項,請使用String.indexOf(String str, int fromIndex) ,將上一個end作為fromIndex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM