I'm trying to parse the configuration files usually found in /etc/default
using java and regular expressions. So far this is the code I have iterating over every line on each file:
// 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));
}
}
}
This works as I expect but I'm pretty sure that I can make this way smaller by using better regular expression but I haven't had any luck. Anyone know of a better way to read these types of files?