2

I want to replace numbers with some math calc based on the numbers.

For example, I have the following text

...
foo 1 42 3
bar 4 5 67
...

Using Ctrl+f tool with the regex (.+) ([\d]+) ([\d]+) ([\d]+), I already can use the values with $1, $2, $3... But I need some way to, for example, sum the values.

If I use a replace regex like Total $1: $2 + $3 + $4, I get:

...
Total foo: 1 + 42 + 3
Total bar: 4 + 5 + 67
...

but actually I want

...
Total foo: 46
Total bar: 76
...

Actually, I don't know if it is possible.

  • 1
    Does this answer your question? [vscode regex sub match evaluate instead of concatenate?](https://stackoverflow.com/questions/35283300/vscode-regex-sub-match-evaluate-instead-of-concatenate) – Myrddin Emrys May 27 '21 at 21:14

2 Answers2

3

Math in regex replace in vscode is not possible (yet?)

There is an open issue in vscode's github: https://github.com/Microsoft/vscode/issues/2902

truth
  • 1,156
  • 7
  • 14
2

I wrote an extension that can do this pretty easily: Find and Transform.

So for the OP's question, you could use this keybinding (in keybindings.json):

{
  "key": "alt+m",                     // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "find": "(.+) (\\d+) (\\d+) (\\d+)",
    "replace": "$${ return `Total $1: ` + ($2 + $3 + $4) }",
    "isRegex": true,

    // "restrictFind": "document"  // or line, selections, once
  }
},

Or you can set that up as a command in your settings.json. See the Readme.

$${ `Total $1: ` + ($2 + $3 + $4) }  

will perform a javascript operation. In this case using $1 as part of a string (delimited by backticks) and adding $2, $3 and $4 as Numbers. Demo:

doing math on a find and replace

Mark
  • 143,421
  • 24
  • 428
  • 436