JGFMK
JGFMK

Reputation: 8904

Why am I getting UnknownFormatConversionException for the following String.format() code?

I was trying to put together a regex expression, which could use repeating patterns via a String format option.

String non_dot = "[^\\.]";
String dot     = "\\.";
String sfp1    = "%1$s*?%2$s";
String sf      = sfp1 + sfp1 + sfp1 + sfp1.substring(0,3) + "*";
System.out.println(sf);
String regex   = String.format(sf, non_dot, dot);
System.out.println(regex);

The output from printing sf is as follows:

%1$s*?%2$s%1$s*?%2$s%1$s*?%2$s%1$*

However, when it comes time to evaluate the String.format(...), for the derivation of the regex variable, my code bombs with:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '1'
    at java.util.Formatter.checkText(Formatter.java:2547)
    at java.util.Formatter.parse(Formatter.java:2533)
    at java.util.Formatter.format(Formatter.java:2469)
    at java.util.Formatter.format(Formatter.java:2423)
    at java.lang.String.format(String.java:2792)
    at Solution.main(Solution.java:23)

I have been using these resources.

According to that, it should work!

Can someone spot why I am getting this error?

Upvotes: 1

Views: 1142

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102903

As @JB Nizet's comment said: Your substring end bound is wrong, and as a result you have %1$* in your format string, which isn't a thing (it's missing an s after the $).

Upvotes: 2

Related Questions