【发布时间】:2010-04-19 16:53:51
【问题描述】:
我正在尝试使用 java 和正则表达式解析通常在 /etc/default 中找到的配置文件。到目前为止,这是我在每个文件的每一行上迭代的代码:
// 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));
}
}
}
这按我的预期工作,但我很确定我可以通过使用更好的正则表达式来缩小这种方式,但我没有任何运气。有人知道读取这些类型文件的更好方法吗?
【问题讨论】:
标签: java regex parsing properties