18

我尝试在 Visual Studio Code 中创建一个简单的正则表达式查找和替换任务。

目前,我将一些用户从 AD 复制到 Visual Studio 代码中的临时文件中,并删除了行首的“CN =”以及第一个“,”之后的所有附加信息(正则表达式:,.*$)。这适用于 VSCode 中的 Find&Replace,但每次我想删除它时我都必须手动输入它。

所以问题是,是否有可能自动化这种任务?我知道有一些外部工具(https://code.visualstudio.com/docs/editor/tasks),但我正在努力让它工作......

编辑:请求的示例(我的正则表达式正在工作,这不是问题:/。我需要一个如何自动化此任务的示例......)

例子

CN=Test User,OU=Benutzer,OU=TEST1,OU=Vert,OU=ES1,OU=HEADQUARTERS,DC=esg,DC=corp

预期产出

Test User
4

4 回答 4

10

这个扩展完成了这项工作:

https://marketplace.visualstudio.com/items?itemName=joekon.ssmacro#overview

正则表达式似乎遵循:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

例子

创建一个文件regex.json

[{
    "command": "ssmacro.replace",
    "args": {
        "info": "strip out EOL whitespace",
        "find": "\\s+$",
        "replace": "",
        "all": true,
        "reg": true,
        "flag": "gm"
    }
}]

"info"只是提醒,没有任何作用。

在keybindings.json中设置快捷方式:

"key": "ctrl+9",
"command": "ssmacro.macro", "args": {"path": "C:\\...\\regex.json"}

您可以将多个命令一起批处理,[{...},{...}]这对于一次性应用一整套正则表达式操作很有用。

于 2018-08-02T16:41:53.000 回答
7

到今天为止,似乎没有扩展仍然是不可能的。除了已接受的答案中提出的扩展之外,还有另外 2 个扩展(两者都是开源的):

批量替换器(但它不适用于在编辑器中打开的文档:“您必须打开一个文件夹进行编辑,并且其中的所有文件都将被更新。” *

替换规则:您只需在您的规则中添加一些规则(使用或settings.json打开调色板并选择)。F1ctrl+shift+pPreferences: open settings (JSON)

"replacerules.rules": {
    "Remove trailing and leading whitespace": {
        "find": "^\\s*(.*)\\s*$",
        "replace": "$1"
    },
    "Remove blank lines": {
        "find": "^\\n",
        "replace": "",
        "languages": [
            "typescript"
        ]
    }
}
于 2019-09-06T14:51:14.943 回答
0

扩展文件夹是:%USERPROFILE%\.vscode\extensions

于 2021-01-28T07:45:38.790 回答
0

这是我编写的一个扩展,它允许您将查找/替换保存在文件中或作为命名命令和/或键绑定搜索文件:Find and Transform。使用 OP 的原始问题,进行此设置(在 中settings.json):

"findInCurrentFile": {                // in settings.json
  "reduceUserEntry": {
    "title": "Reduce User to ...",    // will appear in the Command Palette
    "find": "CN=([^,]+).*",
    "replace": "$1",
    "isRegex": true,
    // "restrictFind": "selections",     // default is entire document
  }
},

您还可以使用此设置对文件进行搜索:

"runInSearchPanel": {
  "reduceUserEntry": {
    "title": "Reduce User to ...",      // will appear in the Command Palette
    "find": "CN=([^,]+).*",
    "replace": "$1",
    "isRegex": true
    
    // "filesToInclude": "${fileDirname}"
    // "onlyOpenEditors": true
    // and more options
  }
}

作为独立的键绑定:

{
  "key": "alt+r",                     // whatever keybinding you want
  "command": "findInCurrentFile",     // or runInSearchPanel
  "args": {
    "find": "CN=([^,]+).*",
    "replace": "$1",   
    "isRegex": true

该扩展还可以运行多个查找/替换 - 只需将它们放入一个数组中:

"find": ["<some find term 1>", "<some find term 2>", etc.

与替换相同,将它们组成一个数组。

于 2022-02-22T21:13:48.250 回答