1

I got a long array of anonymous function in a javascript file and I want to add a name before the functions. I want to go from that

[function(){...}       ,function(){...}      ,...,function(){...}]

to that

[function foo_1(){...},function foo_2(){...},...,function foo_850(){...}]

I'm using Visual Studio Code that allow searching and replacing strings using regexp. I got no problem writing the regexp except for the substitution token that would mean this is the Nth match for your search.

Something like $Nth that will return 1 for first occurence of your search in text. Then 2 and so on.

Or even better $Nth(45) that will start at 45 then 46...

Does such a token exist ?

frenchone
  • 1,547
  • 4
  • 19
  • 34
  • Most programming languages allow you to use a function as the replacement, and it can increment a variable. I don't know how you would do this in a text editor. – Barmar Feb 24 '21 at 23:39
  • You'll need to check the VSCode documentation to see if it provides something like this, it's not something provided by regexp in general. – Barmar Feb 24 '21 at 23:40
  • Regex does not have the concept of a match counter. You'd need to use an external counter. Here is how you can do that with the vim editor: https://stackoverflow.com/a/40656861/7475450 – Peter Thoeny Feb 25 '21 at 00:25

1 Answers1

1

You can use the extension Regex Text Generator

With normal VSC selection select all the function() parts you need.

  • open Find Dialog
  • search for: function(
  • select all occurrences: Alt+Enter

You can limit the find to a selection. First select the part, in the Find Dialog the first thing to do is select Find in Selection (one of the buttons or Alt+L).

Execute the command: Generate text based on Regular Expression (regex)

  • the first Match Expression press: Enter (accept default .*)
  • for the Generator Expression: function foo_{{=i+1}}\( or function foo_{{=i+45}}\(
  • if you like what is generated: Enter
  • if you press Esc the operation is terminated

If you have to do this a lot you can create a key binding with the Regex strings predefined and optionally use the input dialogs to modify the predefined strings

{
    "key": "ctrl+shift+f7",  // or any other key combination
    "when": "editorTextFocus",
    "command": "regexTextGen.generateText",
    "args": {
      "originalTextRegex": ".*",
      "generatorRegex" : "function foo_{{=i+1}}\\(",
      "useInputBox" : true
    }
  }
rioV8
  • 24,506
  • 3
  • 32
  • 49