5

Since Java 15 String.format can be replaced with String#formatted.

Is there an easy way to replace this

String.format("%s foo %s bar", bar(), foo());

with this in IntellIJ IDEA Ultimate?

"%s foo %s bar".formatted(bar(), foo());
0

2 Answers 2

3

For this particular code you can use Regex replacement upon pressing ctrl+R in IntelliJ Idea and clicking the .* icon.

enter image description here

  • The Regex (see the demo): String.format\((\".*\")?\, ?(.*)\);
  • The substitution (in the very same demo): $1.formatted\($2\);

I have to remind you multiple reasons not to do that:

  • Replacing such methods just because it is new has no meaning and brings no benefit. The code will not become more maintainable, more readable and not even faster.
  • Are you sure you need this method? The advantage of this method is when the format pattern of the string is built continuously so the formatted method is comfortable because of a direct use. I describe this in my another answer.
  • Regex based replacement is not safe and reliable in such large scale. The Regex itself also heavily depends on the absence of strange characters right in the formatting pattern itself. Otherwise, you spend a lot of time refining the Regex.

A better way to do if you wish so is to find these methods and replace them manually. In such case, do the full-text search using ctrl+shift+F and make the search based on this pattern:

String\.format

enter image description here

2
  • 1
    It's not limited to one file. You can press ctrl + shift + r and a window will be opened where you can replace this in every file that matches the mask. Oct 31, 2020 at 22:28
  • @genericStackOverflowUser: IntelliJ Idea doesn't stop surprising me. Oct 31, 2020 at 23:00
1

Press ctrl+shift+R to select and replace all occurrences of the text in project at one go.

Replace Text

Select Regex mode and Search Text -

String[.]format[(](.+?),

Replace Text -

$1.formatted\(

N.B I agree with the accepted answer. Regex replacement at large scale is not safe and reliable. I can think of few scenarios where if there is a slight change in the code, the regex replacement in this answer wouldn't work -

Comma inside the format expression

String.format("%s foo, %s bar", bar(), foo());

Extra spaces in between

String.format ( "%s foo, %s bar", bar(), foo());

Code separated by new lines

String.
       format("%s foo %s bar", bar(), foo());

String.format("%s foo " +
                "%s bar", bar(), foo());
2
  • This won’t work if the format string contains a comma, which in my experience is common.
    – Bohemian
    Oct 31, 2020 at 23:37
  • @Bohemian I updated the answer with the risks involved.
    – SKumar
    Nov 1, 2020 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.