• Post Reply Bookmark Topic Watch Topic
  • New Topic

Escape % and other characters in String.format()  RSS feed

 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I have a method B using String.format( ) on some String arrays coming out from other method A.
Now String arr[] returned by A ,can be { "mov" ,"abc"} or {"%mov", "%abc" ,"adc"}.I have no control over it.

In my method B i do -
String rx=String.format("("+ StringUtils.join(arr,"|"))+")"; but it fails with UnknownformatException when it reads "%mov" kind.

How can i escape % like characters without making any changes to A and minimal changes in B.
I know % is used to escape format-specifiers as characters.But my method B is multiple purpose and also used when plain strings come from A .



 
Saloon Keeper
Posts: 7994
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you should pass them as format arguments.

String.format("(%s)", StringUtils.join(arr, "|"));
 
Lucky J Verma
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I figured out if i do
String rx ="(" + StringUtils.join(arr, "|" ) +")";
I get same result.
Are these same?
And
Is this correct to use above - performance wise and programming-style wise?Because In my opinion String.format also calls Formatter and makes it an expensive call.
 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lucky J Verma wrote:I figured out if i do
String rx ="(" + StringUtils.join(arr, "|" ) +")";
I get same result.

I was going to ask you "Why are you calling String.format() at all?". Because I don't see why you would want to call String.format() on that string.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!