vmeghani
vmeghani

Reputation: 85

Java/Groovy String.Format How to handle runtime % in the string to be formatted

Problem that I am facing is that with String.format is a runtime message is having a percent character then it errors out.

For eg. in groovy:

def q = "What are your %age?" 
def percent = 91
println formatMessage("Question: ${q} \n Answer: %d", percent)


String formatMessage(String message, Object... messageParams) {
return String.format(message, messageParams)
}

Now when calling formatMessage if message argument is prepared at runtime from interpolating the string from a variable which is having a valid % character, this results in UnknownFormatConversionException

Now as formatMessage method is getting called at multiple places, we do not want caller to sanitize the message before calling it.

Is there a way to identify and escape % within formatMessage method before calling String.format?

Upvotes: 0

Views: 983

Answers (1)

daggett
daggett

Reputation: 28624

def q = "What are your %age?" 
def percent = 91
println formatMessage("Question: ${q} \n Answer: %d", percent)

@groovy.transform.CompileStatic
String formatMessage(CharSequence message, Object... messageParams) {
    if(message instanceof GString){
        //if message is a GString then build a new one with replaced values
        message=new org.codehaus.groovy.runtime.GStringImpl(
                message.getValues().collect{ it instanceof CharSequence ? it.replaceAll('%','%%') : it } as Object[], 
                message.getStrings()
            )

    }
    return String.format(message as String, messageParams)
}

Upvotes: 1

Related Questions