我嘗試解析窗口INI與Windows下的Java文件。假設內容是:正則表達式在java中:匹配BOL和EOL
[section1]
key1=value1
key2=value2
[section2]
key1=value1
key2=value2
[section3]
key1=value1
key2=value2
我用的是如下因素代碼:
Pattern pattSections = Pattern.compile("^\\[([a-zA-Z_0-9\\s]+)\\]$([^\\[]*)", Pattern.DOTALL + Pattern.MULTILINE);
Pattern pattPairs = Pattern.compile("^([a-zA-Z_0-9]+)\\s*=\\s*([^$]*)$", Pattern.DOTALL + Pattern.MULTILINE);
// parse sections
Matcher matchSections = pattSections.matcher(content);
while (matchSections.find()) {
String keySection = matchSections.group(1);
String valSection = matchSections.group(2);
// parse section content
Matcher matchPairs = pattPairs.matcher(valSection);
while (matchPairs.find()) {
String keyPair = matchPairs.group(1);
String valPair = matchPairs.group(2);
}
}
但它不能正常工作:
的SECTION1不匹配。這可能是因爲這不是從'EOL'之後開始的。當我把
[section1]
之前的空字符串匹配。valSection
返回'\ r \ nke1 = value1 \ r \ nkey2 = value2 \ r \ n'。keyPair
返回'key1'。它看起來像確定。但valPair
根據需要返回'value1 \ r \ nkey2 = value2 \ r \ n',但不返回'value1'。
這裏有什麼問題?
你不排除「新線」的檢查值。 –
廣告2.在'pattPairs'中定義的模式是貪婪的,因此匹配直到第二個鍵的結尾。您可以在貪婪和非貪婪匹配念起來這裏怎麼補償:與http://docs.oracle.com/javase/tutorial/essential/regex/quant.html – Pieter
你嘗試替換'\ r \ N'首先是\ n? – Thomas