Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MessageFormat not formatting when single quotes are included

Tags:

java

I am passing in text which is combination of {} filler and text. I am trying to fill {} with some values and tried using MessageFormat.

String sss = "{0}SomeText{1}\'.{2}SomeText{2}SomeText{0}{0}SomeText{2}{0}SomeText{0}{1}SomeText{0}{2}{0}{0}{1}{0}{2}{0}{0}{2}{0}{0}{1}{0}{2}{0}";

Object[] testArgs = {"nits1", "Nits2","nits#"};

System.out.println(MessageFormat.format(sss,testArgs));

OUTPUT

nits1SomeTextNits2.{2}SomeText{2}SomeText{0}{0}SomeText{2}{0}SomeText{0}{1}SomeText{0}{2}{0}{0}{1}{0}{2}{0}{0}{2}{0}{0}{1}{0}{2}{0}
like image 467
Dev G Avatar asked Jun 12 '12 11:06

Dev G


2 Answers

The single quote must be escaped using a double single quote:

String sss = "{0}SomeText{1}''.{2}S..."
like image 109
JB Nizet Avatar answered Oct 16 '22 22:10

JB Nizet


My mistake was, that I didn't use the returned value from method 'format(..)'

Wrong code:

MessageFormat.format(sss, testArgs);
System.out.println(sss);

Correct code:

String newString = MessageFormat.format(sss, testArgs);
System.out.println(newString);
like image 23
Adir D Avatar answered Oct 17 '22 00:10

Adir D