I would like to write a function, that can match a string against regex and execute a callback with all group matches as parameters.
I came up with this and it works:
private static void parse(String source, String regex,
Consumer<String[]> callback) {
//convert regex groups 1..n into integer array 0..n-1 and call
//consumer callback with this array
Matcher m = Pattern.compile(regex).matcher(source);
String[] ret = new String[m.groupCount()];
if (m.matches()) {
for (int i=0; i<m.groupCount(); i++) {
ret[i] = m.group(1+i);
}
callback.accept(ret);
}
}
You can then do
parse("Add 42,43", "Add (\\d+?),(\\d+?)", p -> processData(p[0],p[1]));
What I would like to be able to do ideally is this
parse("Add 42,43", "Add (\\d+?),(\\d+?)", (x,y) -> processData(x,y));
What would be the most elegant way? The only one I can think of is to declare multiple functional interfaces with 1..n parameters and use overrides to handle it. Any better ideas, maybe with reflection?
processDatabe called, as it seems to require two args?