aspose file tools
The moose likes Beginning Java and the fly likes Escape % and other characters in String.format() Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Escape % and other characters in String.format()" Watch "Escape % and other characters in String.format()" New topic
Author

Escape % and other characters in String.format()

Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 277
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 .



Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3044
    
    1

You should pass them as format arguments.

String.format("(%s)", StringUtils.join(arr, "|"));
Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 277
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.
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12907
    
    3

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Escape % and other characters in String.format()
 
Similar Threads
Regular expressions retrieval in java
Problem with escape chars...
split the string
2 dimensional array
Reading data from a file and storing into array of strings problem