简体   繁体   中英

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?

正如@JB Nizet 的评论所说:您的子字符串结束边界是错误的,因此您的格式字符串中有%1$* ,这不是一回事(它在$之后缺少一个s )。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM