正規表現を使用して、INI ファイル内のセクション ブロックを一致させようとしています。本正規表現クックブックに記載されているレシピを使用していますが、うまくいかないようです。
私が使用しているコードは次のとおりです。
final BufferedReader in = new BufferedReader(
new FileReader(file));
String s;
String s2 = "";
while((s = in.readLine())!= null)
s2 += s + System.getProperty("line.separator");
in.close();
final String regex = "^\\[[^\\]\r\n]+](?:\r?\n(?:[^\r\n].*)?)*";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
String sectionBlock = null;
final Matcher regexMatcher = pattern.matcher(s2);
if (regexMatcher.find()) {
sectionBlock = regexMatcher.group();
}
入力ファイルの内容は次のとおりです。
[Section 2]
Key 2.0=Value 2.0
Key 2.2=Value 2.2
Key 2.1=Value 2.1
[Section 1]
Key 1.1=Value 1.1
Key 1.0=Value 1.0
Key 1.2=Value 1.2
[Section 0]
Key 0.1=Value 0.1
Key 0.2=Value 0.2
Key 0.0=Value 0.0
問題はsectionBlock
、最初のセクションだけでなく、ファイルの内容全体と等しくなってしまうことです。
(それが重要かどうかはわかりませんが、Windows でこれを行っており、行区切り文字はs2
"\r\n" と同じです (少なくとも、IDEA デバッガーはそのように表示します)。)
ここで何が間違っていますか?