Search code examples
javamessageformat

Named message params


I was often using MessageFormat for indexed params in situations like this:

String text = MessageFormat.format("The goal is {0} points.", 5);

Now I encountered a situation where I need to handle messages which are in the following format:

"The {title} is {number} points."

So, values are not indexed anymore and placeholders are strings. How can I handle this situation and have the same functionality like with MessageFormat? MessageFormat throws parse exception if params are not indexed.

Thank you.


Solution

  • A simple suggestion would consist of replacing the text parameter as index with a regex match and then use it as you would normally. Here an example :

    int paramIndex = 0;
    
    String text = "The {title} is {number} points.";
    String paramRegex = "\\{(.*?)\\}";
    Pattern paramPattern = Pattern.compile(paramRegex);
    Matcher matcher = paramPattern.matcher(text);
    
    while(matcher.find())
        text = text.replace(matcher.group(), "{" + paramIndex++ + "}");
    
    text = MessageFormat.format(text, "kick", "3");
    

    In that case, text would be equals to "The kick is 3 points" at the end.