匹配INI区块

Pau*_*ers 0 java regex ini

我正在使用正则表达式来尝试匹配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();
}
Run Code Online (Sandbox Code Playgroud)

以下是我的输入文件的内容:

[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
Run Code Online (Sandbox Code Playgroud)

问题是sectionBlock最终等于文件的整个内容,而不仅仅是第一部分.

(我不知道它是否重要,但是我在Windows上执行此操作并且行分隔符s2等于"\ r \n"(至少,这是IDEA调试器显示的内容).)

我在这做错了什么?

Bar*_*ers 5

试试这个正则表达式:

(?ms)^\[[^]\r\n]+](?:(?!^\[[^]\r\n]+]).)*
Run Code Online (Sandbox Code Playgroud)

或Java String文字正则表达式:

"(?ms)^\\[[^]\r\n]+](?:(?!^\\[[^]\r\n]+]).)*"
Run Code Online (Sandbox Code Playgroud)

(简短)解释:

(?ms)          // enable multi-line and dot-all matching
^              // the start of a line
\[             // match a '['
[^]\r\n]+      // match any character except '[', '\r' and '\n', one or more times
]              // match a ']'
(?:            // open non-capturing group 1
  (?!          //   start negative look-ahead
    ^          //     the start of a line
    \[         //     match a '['
    [^]\r\n]+  //     match any character except '[', '\r' and '\n', one or more times
    ]          //     match a ']'
  )            //   stop negative look-ahead
  .            //   any character (including line terminators)
)*             // close non-capturing group 1 and match it zero or more times
Run Code Online (Sandbox Code Playgroud)

用简单的英语写成:

匹配'['后跟一个或多个字符,除了'[','\ r'和'\n',然后是']'(让我们称之为匹配X).然后对于文本中的每个空字符串,首先向前看,看看你是否没有看到匹配X,如果没有,则匹配任何字符.