Visual Studio代码:如何自动化一个简单的regex查找和替换?

kx7yvsdv  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(135)

我尝试在Visual Studio Code中创建一个简单的regex查找和替换任务。
目前,我从AD中复制一些用户到Visual Studio代码中的临时文件中,并删除行开头的“CN=”和第一个“,”(regex:,.*$)之后的所有权限信息。这在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

nkkqxpd9

nkkqxpd91#

这个扩展可以完成这项工作:ssmacro
正则表达式似乎遵循JavaScript 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"}


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

ou6hu8tu

ou6hu8tu2#

到今天为止,似乎没有扩展仍然是不可能的。这里有两个除了公认答案中提出的扩展之外的其他扩展(两者都是开源的):

  • 批量替换(但它不适用于在编辑器中打开的文档:“您必须打开一个文件夹进行编辑,并且其中的所有文件都将被更新。”*
  • 替换规则:您只需在settings.json中添加一些规则(使用F1ctrl+shift+p打开调色板并选择Preferences: open settings (JSON))。
"replacerules.rules": {
    "Remove trailing and leading whitespace": {
        "find": "^\\s*(.*)\\s*$",
        "replace": "$1"
    },
    "Remove blank lines": {
        "find": "^\\n",
        "replace": "",
        "languages": [
            "typescript"
        ]
    }
}

字符串

u0njafvf

u0njafvf3#

这里是我写的一个扩展,允许你保存查找/替换文件或搜索文件作为一个命名的命令和/或作为一个键绑定:查找和转换。使用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.
同样的替换也是一样的,把它们做成一个数组。

相关问题