IntelliJ IDEA
 
Get IntelliJ IDEA

Work with structural search and replace

Last modified: 26 May 2024

The structural search and replace is a powerful tool that can search for a specific pattern of code and add modifiers that can narrow your search.

In this tutorial we will search for field declarations, add modifiers, and create a code inspection based on the modified template. If you want, you can watch the related video before we dive in. The video might slightly differ since it was done for the earlier version of IntelliJ IDEA.

Let's open the Search Structurally dialog and use one of the existing templates for our search.

Now, let's return to our structural search dialog to alter the predefined template a bit. By the way, we can use the Search Everywhere window to access the search dialog.

With the structural search, we can conduct some interesting searches. Let's choose another existing template (method calls) as our example.

Let's assume we're doing this search to replace all these method calls with logging calls instead of System.out. The logging methods take only strings and no other types.

First, let's find methods that pass the string.

Now let's do our replacement.

We can save this template to refer to it later if we need.

We can also use our template as an inspection, so when we come across the same code, we'll see a warning and can quickly replace the code.

We can add a custom structural search inspection right from the inspections settings.

We can run our inspection separately using its name.