So what’s cooler than substituting placeholders with variables? Getting those variables out from a parsed string! Oh yeah!

In the previous code example, Fun With MessageFormat, we looked at using MessageFormat to format strings by replacing markers with the given variables.

But what if we want to work the other way around? No problem at all!

MessageFormat allows us to parse formatted messages in order to extract the variables that were used to create it. Have a look at the code snippet below.


String pattern = 'Greetings {0}! You are visitor no ' + '{1,number,integer}. The time is now {2,date,full}.';
MessageFormat mf = new MessageFormat(pattern);
Object[] params = new Object[] {'Bob', 23,
GregorianCalendar.getInstance().getTime() };

String parsedMsg = mf.format(params);
System.out.println(parsedMsg);
Object[] obj;
try {
// The fun starts here
 obj = mf.parse(parsedMsg);
 for (Object o : obj) {
 System.out.println(o.toString());

} catch (ParseException e) {
 e.printStackTrace();
}

An important point to note is that instead of using the static format(…) method, we now create an instance of the MessageFormat class and initialize it with our pattern.

We make use of the parse(String source) method. This method will parse the given string from the beginning. You are returned an Object array containing the variables.

It’s pretty simple stuff.

As always, refer to the API documentation to gain a deeper understanding.

Go forth and prosper!

Leave a Reply

Your email address will not be published. Required fields are marked *