简体   繁体   English

"VSCode:替换文本做数学"

[英]VSCode: Replace text doing math

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.使用Ctrl+f工具和正则表达式(.+) ([\\d]+) ([\\d]+) ([\\d]+) ,我已经可以使用$1$2$3的值......但是例如,我需要一些方法来对这些值求和。

If I use a replace regex like Total $1: $2 + $3 + $4 , I get:如果我使用像Total $1: $2 + $3 + $4这样的替换正则表达式,我会得到:

...
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.实际上,我不知道这是否可能。

Math in regex replace in vscode is not possible (yet?) 无法在vscode中使用正则表达式中的数学替换(还好吗?)

There is an open issue in vscode's github: https://github.com/Microsoft/vscode/issues/2902 vscode的github中有一个未解决的问题: https : //github.com/Microsoft/vscode/issues/2902

I wrote an extension that can do this pretty easily: Find and Transform .我写了一个可以很容易做到这一点的扩展: Find and Transform

So for the OP's question, you could use this keybinding (in keybindings.json ):因此,对于 OP 的问题,您可以使用此键绑定(在keybindings.json中):

{
  "key": "alt+m",                     // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "find": "(.+) (\\d+) (\\d+) (\\d+)",
    "replace": "$${ `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 .或者,您可以在settings.json中将其设置为命令。 See the Readme.请参阅自述文件。

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

will perform a javascript operation.将执行 javascript 操作。 In this case using $1 as part of a string (delimited by backticks) and adding $2, $3 and $4 as Numbers.在这种情况下,使用$1作为字符串的一部分(由反引号分隔)并添加$2, $3 and $4作为数字。 Demo:演示:

在查找和替换上做数学

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM