intellij-ideareplacestructural-search

Is there a way to add 1 to a string containing numbers in find and replace in intellij?


I have code that looks like this:

public void testSomething1() {

}

public void testSomething2() {

}

public void testSomething3() {

}

And I want the result to look like this with find and replace:

public void testSomething2() {

}

public void testSomething3() {

}

public void testSomething4() {

} I need this because I just realized I needed to add another test between 2 and 3 and leave the rest intact. I wish I could add it at the end, but I can't, I have to use this test generation tool and implement the tests for a school project. I have 51 tests and I don't want to shift n + 1 manually for ever test, especially since theres a comment referring to the number. Oh please tell me there's a way T_T. Thank you!


Solution

  • You could use Edit | Find | Replace Structurally for this. Use a template like the following:

    <replaceConfiguration name="Counting" text="void $method$();" recursive="false" type="JAVA" pattern_context="member" reformatAccordingToStyle="false" shortenFQN="false" replacement="void $replacement$();">
      <constraint name="__context__" within="" contains="" />
      <constraint name="method" regexp="(testSomething)(\d+)" within="" contains="" />
      <variableDefinition name="replacement" script="&quot;def (_,name, number) = (method.name =~ /(\p{L}+)(\d+)/)[0]&#10;name + (Integer.parseInt(number) + 1)&#10;&quot;" />
    </replaceConfiguration>
    

    You can copy this pattern and use the Import Template from Clipboard action in the menu under the tool button of the Structural Search dialog.