Reputation: 3819
I have strings like:
"{0}_something_{1}-{2}-something"
and i need to convert these strings to
"%s_something_%s-%s-something"
what is the best way to do this?
Upvotes: 0
Views: 231
Reputation: 45589
String str = "{0}something{1}-{2}-something";
String clean = str.replaceAll("(\\{\\d+\\}-?)", "%s_");
System.out.println(clean); // outputs: %s_something%s_%s_something
Upvotes: 1
Reputation: 10949
I would use a regexp.
String data = "{0}something{1}-{2}-something";
System.out.println(data.replaceAll("\\{.*?\\}", "%s_"));
Output:
%s_something%s_-%s_-something
Edit:
A regexp that only replaces if there only are digits between {
and }
System.out.println(data.replaceAll("\\{\\d+\\}", "%s_"));
Upvotes: 4
Reputation: 55956
String result = MessageFormat.format("{0}something{1}-{2}-something", "%s_", "_%s", "%s");
Upvotes: 1
Reputation: 354506
myString.replaceAll("\\{\\d\\}", "%s")
If you're trying to create a Java format string, then you should probably retain the order of those replacements, otherwise strings like foo {2} bar {1} baz {0}
will pose problems:
myString.replaceAll("\\{(\\d)\\}", "%$1$$s");
Upvotes: 6
Reputation: 888
Consider using MessageFormat. - http://download.oracle.com/javase/6/docs/api/java/text/MessageFormat.html
Upvotes: 0