Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the Java equivalent of sscanf for parsing values from a string using a known pattern?

Tags:

java

scanf

So I come from a C background (originally originally, though I haven't used that language for almost 5 years) and I'm trying to parse some values from a string in Java. In C I would use sscanf. In Java people have told me "use Scanner, or StringTokenizer", but I can't see how to use them to achieve my purpose.

My input string looks like "17-MAR-11 15.52.25.000000000". In C I would do something like:

sscanf(thestring, "%d-%s-%d %d.%d.%d.%d", day, month, year, hour, min, sec, fracpart); 

But in Java, all I can do is things like:

scanner.nextInt(); 

This doesn't allow me to check the pattern, and for "MAR" I end up having to do things like:

str.substring(3,6); 

Horrible! Surely there is a better way?

like image 731
Adam Burley Avatar asked Dec 08 '11 11:12

Adam Burley


2 Answers

The problem is Java hasn't out parameters (or passing by reference) as C or C#.

But there is a better way (and more solid). Use regular expressions:

Pattern p = Pattern.compile("(\\d+)-(\\p{Alpha}+)-(\\d+) (\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)") Matcher m = p.matcher("17-MAR-11 15.52.25.000000000"); day = m.group(1); month= m.group(2); .... 

Of course C code is more concise, but this technique has one profit: Patterns specifies format more precise than '%s' and '%d'. So you can use \d{2} to specify that day MUST be compose of exactly 2 digits.

like image 168
korifey Avatar answered Sep 22 '22 12:09

korifey


Here is a solution using scanners:

Scanner scanner = new Scanner("17-MAR-11 15.52.25.000000000");  Scanner dayScanner = new Scanner(scanner.next()); Scanner timeScanner = new Scanner(scanner.next());  dayScanner.useDelimiter("-"); System.out.println("day=" + dayScanner.nextInt()); System.out.println("month=" + dayScanner.next()); System.out.println("year=" + dayScanner.nextInt());  timeScanner.useDelimiter("\\."); System.out.println("hour=" + timeScanner.nextInt()); System.out.println("min=" + timeScanner.nextInt()); System.out.println("sec=" + timeScanner.nextInt()); System.out.println("fracpart=" + timeScanner.nextInt()); 
like image 42
dsboger Avatar answered Sep 20 '22 12:09

dsboger