Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Java library for parsing printf format strings?

Tags:

java

printf

I'm writing an emulator for a machine with a 'printf' opcode, and while I'm aware of the Formatter class which will probably be good enough for actually formatting the strings, I need a way to count the number of arguments which are consumed by the printf call.

Off the top of my head, I could probably do something with a regex to count the number of '%'s, but I'm not too familiar with format strings, so I might not count properly... (excluding escaped ones, etc)

edit: I actually need the number of parameter, along with a mapping of parameter # to parameter type, so, for example, "hello %s %+.3i" would give {0 -> String, 1 -> Integer}

like image 406
Bwmat Avatar asked Apr 01 '12 23:04

Bwmat


2 Answers

Format Strings interpret every % as a placeholder, with literal % being escaped as %%, so it should be as simple as this:

String formatString;
int parameterCount = formatString.replace("%%", "").split("%").length - 1;

This code first removes all escaped (doubled) %, then counts % via split.

like image 142
Bohemian Avatar answered Sep 30 '22 20:09

Bohemian


Why don't you just use a Regex that is something like %(?:%|[0-9]+([dox])) and examine the format type specifier that way?

There was another SO topic about parsing sprintf format strings with regex's which might give you some more ideas. Unless you specify what features of printf() you want, it's sort of hard to recommend an exact regex.

Or, as I mentioned in my comment, if you're using another compiler tool anyway like ANTLR or Parboiled, use that to deconstruct the format string into appropriate pieces via a simple grammar specification.

like image 34
Jason S Avatar answered Sep 30 '22 18:09

Jason S