Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a string pattern with increasing integers using regex

I have multiple .xml files in which I have a repeating string pattern. I want to replace each instance of that pattern with an integer starting with "1".

e.g.

Input:

APPLE is my favorite fruit. APPLE is red in color.

Expected Output:

1 is my favorite fruit. 2 is red in color.
like image 552
Siddharth Patki Avatar asked Nov 19 '25 04:11

Siddharth Patki


1 Answers

For simple incrementing integers from 1, 2, 3, ... (or 0, 1, 2, ...) you can use the new snippet variables $CURSOR_NUMBER or $CURSOR_INDEX respectively.

You would still have to find a way to select all the find matches you want to replace (and so I think the extension below is better). You could use Ctrl+D to progressively select the occurrences you want or using the Find Widget:

Find: APPLE

and then Alt+Enter to select all matches and then insert a snippet like:

"Increment integer": {
    "prefix": "i++",
    "body": [
        "${CURSOR_NUMBER}",
    ]
},

by typing its trigger prefix i++ and voila, all the APPLE instances are replaced by increasing integers.


I am sure there are other extensions that can do this, but using one that I wrote this is very easy: Find and Transform.

Create this keybinding (in your keybindings.json):

{
  "key": "alt+y",                   // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    // "find": "APPLE",            // actually not necessary
    "replace": "${matchNumber}",
    "matchCase": true              // match only APPLE, not Apple
  }
}

That will replace whatever word your cursor is on with the matchNumber starting at 1. If you wanted to start at 0, use ${matchIndex}.

If you need to specify a more complicated regex find, you can do that too.

enter image description here

like image 124
Mark Avatar answered Nov 21 '25 09:11

Mark