If you want a regex which captures the third field only and nothing else, you could use the following:
String regex = "(?:[^\\t]*)\\t(?:[^\\t]*)\\t([^\\t]*)\\t(?:[^\\t]*)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.err.println(matcher.group(1));
}
I don't know whether this would perform any better than split("\\t")
for parsing a large file.
UPDATE
I was curious to see how the simple split versus the more explicit regex would perform, so I tested three different parser implementations.
/** Simple split parser */
static class SplitParser implements Parser {
public String parse(String line) {
String[] fields = line.split("\\t");
if (fields.length == 4) {
return fields[2];
}
return null;
}
}
/** Split parser, but with compiled pattern */
static class CompiledSplitParser implements Parser {
private static final String regex = "\\t";
private static final Pattern pattern = Pattern.compile(regex);
public String parse(String line) {
String[] fields = pattern.split(line);
if (fields.length == 4) {
return fields[2];
}
return null;
}
}
/** Regex group parser */
static class RegexParser implements Parser {
private static final String regex = "(?:[^\\t]*)\\t(?:[^\\t]*)\\t([^\\t]*)\\t(?:[^\\t]*)";
private static final Pattern pattern = Pattern.compile(regex);
public String parse(String line) {
Matcher m = pattern.matcher(line);
if (m.matches()) {
return m.group(1);
}
return null;
}
}
I ran each ten times against the same million line file. Here are the average results:
- split: 2768.8 ms
- compiled split: 1041.5 ms
- group regex: 1015.5 ms
The clear conclusion is that it is important to compile your pattern, rather than rely on String.split, if you are going to use it repeatedly.
The result on compiled split versus group regex is not conclusive based on this testing. And probably the regex could be tweaked further for performance.
UPDATE
A further simple optimization is to re-use the Matcher rather than create one per loop iteration.
static class RegexParser implements Parser {
private static final String regex = "(?:[^\\t]*)\\t(?:[^\\t]*)\\t([^\\t]*)\\t(?:[^\\t]*)";
private static final Pattern pattern = Pattern.compile(regex);
// Matcher is not thread-safe...
private Matcher matcher = pattern.matcher("");
// ... so this method is no-longer thread-safe
public String parse(String line) {
matcher = matcher.reset(line);
if (matcher.matches()) {
return matcher.group(1);
}
return null;
}
}