【问题标题】:VSCode: Replace text doing mathVSCode:替换文本做数学
【发布时间】:2019-07-18 01:33:35
【问题描述】:

我想用一些基于数字的数学计算来替换数字。

例如,我有以下文字

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

使用带有正则表达式(.+) ([\d]+) ([\d]+) ([\d]+)Ctrl+f 工具,我已经可以使用带有$1$2$3 的值...但是我需要一些方法来对这些值求和。

如果我使用 Total $1: $2 + $3 + $4 之类的替换正则表达式,我会得到:

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

但其实我想要

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

其实我也不知道有没有可能。

【问题讨论】:

标签: regex replace visual-studio-code


【解决方案1】:

我写了一个可以很容易做到这一点的扩展:Find and Transform

所以对于 OP 的问题,您可以使用这个键绑定(在 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
  }
},

或者您可以在settings.json 中将其设置为命令。请参阅自述文件。

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

将执行 javascript 操作。在这种情况下,使用$1 作为字符串的一部分(由反引号分隔)并将$2, $3 and $4 添加为数字。演示:

【讨论】:

    【解决方案2】:

    在 vscode 中的正则表达式替换中的数学是不可能的(还没有?)

    vscode 的 github 中有一个未解决的 issue:https://github.com/Microsoft/vscode/issues/2902

    【讨论】:

      猜你喜欢
      • 2019-01-02
      • 2016-04-09
      • 2014-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 2019-07-25
      相关资源
      最近更新 更多