Escape% character in java string to use String.format

In my project (Java / Play framework) I have an error routing that checks the response from the web service, if the response is an error code, we display the corresponding error message, which said that there was a problem when entering the user, the service checks the validity of user input.

When the user enters the% character, this logic is interrupted because the error display logic uses

String.format(message, messageArgs); 

What interpolates messageArgs, enter a String message where it finds%, and if messageArgs contains%, I also get an exception.

I need to clean, remove or otherwise remove% of user inputs before displaying a message.

: The requested email address% s is not valid. messageArgs: orlybg%@gmail.com

Any tips on how to do this in Java in the simplest, shortest way?

here is part of the error log

  java.util.UnknownFormatConversionException: Conversion = 'i' at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2646) at java.util.Formatter$FormatSpecifier.<init>(Formatter.java:2675) at java.util.Formatter.parse(Formatter.java:2528) at java.util.Formatter.format(Formatter.java:2469) at java.util.Formatter.format(Formatter.java:2423) at java.lang.String.format(String.java:2797) at controllers.api.PublicAPI.renderAPIError(PublicAPI.java:176) at controllers.api.DeviceAPI.setEmailAddress(DeviceAPI.java:736) at play.mvc.ActionInvoker.invokeWithContinuation(ActionInvoker.java:557) at play.mvc.ActionInvoker.invoke(ActionInvoker.java:508) at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:484) at play.mvc.ActionInvoker.invokeControllerMethod(ActionInvoker.java:479) at play.mvc.ActionInvoker.invoke(ActionInvoker.java:161) at Invocation.HTTP Request(Play!) 

Thanks!

+6
source share
3 answers

In a String message, the% character is escaped with another%. So you need to double it: %%
For example: "Bla bla% i bla" → "Bla bla %% i bla"
There is no problem with the% sign in messageArgs String, and you do not need to avoid it

+5
source

If you get java.util.UnknownFormatConversionException: Conversion = 'i' , maybe you are using %i in your message trying to format an integer, this is not true. You must use %d to format the integer decimal. The full supported conversion specification can be found here .

+1
source

Use %% in the format string when you need to print the string % :

 String.format("sendOneSuccessCountRate: %7.2f%%" ,sendOneSuccessCountRate //0.95 ); 

will give you 95.00%

+1
source

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


All Articles