Siddharth Patki
Siddharth Patki

Reputation: 33

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.

Upvotes: 3

Views: 970

Answers (2)

Mark
Mark

Reputation: 182331

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

Upvotes: 4

rioV8
rioV8

Reputation: 28783

With Regex Text Generator you can do this.

  • select all the APPLE instances you want, any way you like, Ctrl+D, Selet All Occurrences, Alt+Enter from Find dialog
  • execute command Generate Text based on regular expression
  • as match expression use: .*
  • as generator expression use: {{=i+1}}

Upvotes: 1

Related Questions