我試圖解析通常在/etc/default
中使用java和正則表達式找到的配置文件。到目前爲止,這是我對每個文件的每一行遍歷代碼:解析文件「/ etc/default」使用java
// remove comments from the line
int hash = line.indexOf("#");
if (hash >= 0) {
line = line.substring(0, hash);
}
// create the patterns
Pattern doubleQuotePattern = Pattern.compile("\\s*([a-zA-Z_][a-zA-Z_0-9]*)\\s*=\\s*\"(.*)\"\\s*");
Pattern singleQuotePattern = Pattern.compile("\\s*([a-zA-Z_][a-zA-Z_0-9]*)\\s*=\\s*\\'(.*)\\'\\s*");
Pattern noQuotePattern = Pattern.compile("\\s*([a-zA-Z_][a-zA-Z_0-9]*)\\s*=(.*)");
// try to match each of the patterns to the line
Matcher matcher = doubleQuotePattern.matcher(line);
if (matcher.matches()) {
System.out.println(matcher.group(1) + " == " + matcher.group(2));
} else {
matcher = singleQuotePattern.matcher(line);
if (matcher.matches()) {
System.out.println(matcher.group(1) + " == " + matcher.group(2));
} else {
matcher = noQuotePattern.matcher(line);
if (matcher.matches()) {
System.out.println(matcher.group(1) + " == " + matcher.group(2));
}
}
}
這個工程,我希望,但我敢肯定,我可以讓這樣小的通過使用更好的正則表達式,但我的天堂」沒有任何運氣。任何人都知道更好的方式來閱讀這些類型的文件?
偉大的...它的作品非常漂亮。這就是我非常喜歡的原因。偉大的人寫偉大的代碼。 – rmarimon 2010-04-19 21:14:38
快樂這是你正在尋找,快速注意該模式確實允許不平衡的報價(我原本有一個錯別字,它沒有,我已經修復)。 – 2010-04-20 11:01:32