Tuesday, June 17, 2008

Java Regular Expressions

Here is how you can use regular expression in Java to parse a file.

The file I'm parsing looks like this. Some of you may recognize this as the output of bhosts from an LSF farm.

HOST_NAME STATUS JL/U MAX NJOBS RUN SSUSP USUSP RSV
my-host ok - 4 0 0 0 0 0


To parse this I use the following:

Pattern pattern = Pattern.compile("(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
// now matcher.group(1) holds the first one matched etc.
}

No comments: