Search code examples
intellij-ideastructural-search

How to use IntelliJ's structural replacement for "all matches, except..."?


Lets say I want to replace print(x) with print(wrapper(x)). I can match

print($Argument$)

and replace it with

print(wrapper($Argument$))

However, if I already have a call to print(wrapper(x)), I don't want to replace that with print(wrapper(wrapper(x))). How can I avoid that? In other words, how do I say "do the replacement, unless the arguments match some pattern"?


Solution

  • You would:

    1. Input search template (for example): System.out.println($args$)
    2. Click Edit Variables
    3. Choose the $args$ variable
    4. Under Text constraints -> Text/regexp enter ^wrapper\(.*\)$ and tick Invert condition

    Obviously you can tweak that regex to whatever you want. Invert condition means that the search will skip all instances where condition is met. Basically you write a regex to match what you don’t want to see and Invert condition is a NOT operator.

    On my test text:

    System.out.println( ex.getMessage() );
    System.out.println( wrapper( ex.getMessage() ) );
    

    The second instance was not in the search results.