Parsing files "/etc/default" using java

Posted by rmarimon on Stack Overflow See other posts from Stack Overflow or by rmarimon
Published on 2010-04-19T16:53:51Z Indexed on 2010/04/19 17:13 UTC
Read the original article Hit count: 399

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about parsing