在家加班會有點不甘願,但研究和工作有關的技能倒還可以。Java在Regex的跨行比對有點彆扭,用來解析非XML、具Block性質的配置檔會比較清晰。需求如下:

*
*
Definition for table TESTUTF8.T1
Record length: 112
Syskey: 0
Columns: 2
C1   64     50        0  0  0 1 0     50     50     50 0 0 0 0 1    0 1 2
C2   64     50       56  0  0 1 0     50     50      0 0 0 0 0 1    0 0 0
End of definition

* TEST T2
Definition for table TESTUTF8.T2
Record length: 112
Syskey: 0
Columns: 2
C1   64     50        0  0  0 1 0     50     50     50 0 0 0 0 1    0 1 2
C2   64     50       56  0  0 1 0     50     50      0 0 0 0 0 1    0 0 0
End of definition

  如何在Java去group上述粗黑字的多行字串?逆向思考,跨行比對其實就是把它們當作一個單行,在Perl是用m(mulitline)參數,在Java使用Pattern物件要帶Patter.DOTALL參數,dot是一點,表示連換行字元都列入比對範圍,是故要group上述的需求的Sample code如下:

import java.io.FileInputStream;
import java.io.StringReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestRegexMultiLines {

    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("D:/javaue.def");
        byte[] ba = new byte[fis.available()];
        fis.read(ba);
        String javadef = new String(ba);
       
Pattern pat = Pattern.compile("Definition for table .*?End of definition",
            Pattern.DOTALL);

        Matcher mat = pat.matcher(javadef);
        while (mat.find()) {
            System.out.println("========================");
            System.out.println(mat.group());
        }
    }
}

  這樣就能找到兩筆group,因為有Pattern.DOTALL,小數點比對就包括了換行字元。另一個是*?這個不貪多量詞,找到符合pattern的最小字串,否則會變成找到一筆group,包括非粗體字都被包括進去。
arrow
arrow
    全站熱搜

    Jemmy 發表在 痞客邦 留言(0) 人氣()