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());

2 Answers2

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

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
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());
SKumar
  • 1,940
  • 1
  • 7
  • 12