Is there a Java library for parsing printf format strings?

I am writing an emulator for a machine with the printf opcode, and although I know the Formatter class, which is probably good enough for the actual formatting of strings, I need a way to count the number of arguments that are consumed by printf.

At the top of my head, I could do something with a regex to count the number of “%”, but I'm not too familiar with format strings, so I could not count correctly ... (excluding escaped, etc. )

edit: I really need the number of parameters, as well as matching the parameter # with the type of the parameter, so for example, "hello% s% +. 3i" will give {0 → String, 1 → Integer}

+6
source share
2 answers

Why don't you just use Regex, something like %(?:%|[0-9]+([dox])) , and study this type of format specifier?

There was another topic about sprintf parsing with regex , which might give you some more ideas. Unless you specify which printf () functions you need, it is difficult to recommend an exact regular expression.

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

+1
source

To format strings, interpret each % as a placeholder, with the 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) % , and then counts % through split.

+7
source

Source: https://habr.com/ru/post/912194/


All Articles