Thanks
Solved the problem using regular expressions. It is *really* a pity
that Java does not have a method that is similar to the sscanf() of the
C language, since in my opinion, sscanf() is easier to parse strings
than regular exp.
To the best of my knowledge there isn't one either. But you can always
write something close...even sscanf in C is just a library function.
For example:
**************************************************
package org.ahs.scanner;
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ScannerUtils {
public static Object[] sscanf(String input, String format) {
String formatCopy = new String(format);
Scanner sc = new Scanner(input);
String afterStrings = format.replaceAll("%s", "(\\\\w+)");
String afterDoubles =
afterStrings.replaceAll("%f", "(\\\\d+\\\\.\\\\d+)");
String finalFormat = afterDoubles.replaceAll("%d", "(\\\\d+)");
sc.findInLine(finalFormat);
MatchResult sw = sc.match();
Object[] results = new Object[sw.groupCount()];
Pattern formatPattern = Pattern.compile("(%[dfs])");
Matcher formatMatcher = formatPattern.matcher(formatCopy);
int i = 0;
while(formatMatcher.find()) {
int start = formatMatcher.start();
String found = formatCopy.substring(start, start+2);
if (found.equals("%s")) {
results
= sw.group(++i);
} else if (found.equals("%d")) {
results = Integer.parseInt(sw.group(++i));
} else if (found.equals("%f")) {
results = Double.parseDouble(sw.group(++i));
} else {
break;
}
}
return results;
}
}
**************************************************
public static void main(String[] args) {
Object[] values = ScannerUtils.sscanf(
"Arved has 5 boxes weighing a total of 15.55 kg",
"%s has %d %s weighing a total of %f %s");
System.out.printf("Name = '%s'\n", values[0]);
System.out.printf("Item number = '%d'\n", values[1]);
System.out.printf("Item Type = '%s'\n", values[2]);
System.out.printf("Mass = '%f'\n", values[3]);
System.out.printf("Unit = '%s'\n", values[4]);
}
**************************************************
results in:
Name = 'Arved'
Item number = '5'
Item Type = 'boxes'
Mass = '15.550000'
Unit = 'kg'
It's not identical, of course...you don't have nice variable names to
refer to, rather array elements. But you've got a format string you're
familiar with.
Don't take the above as a robust piece of code - it's more illustrative
than anything. Some extra error checking or informative messages would be
good.
AHS