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}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With