简体   繁体   中英

Visual Studio Code: How to automate a simple regex-find and replace?

I try to create a simple regex-find and replace task in Visual Studio Code.

Currently I copy from the AD some Users to a temporary file in Visual Studio code and remove the "CN=" at the beginning of the line and all the aditional informations after the first "," (regex: ,.*$). This works fine with Find&Replace in VSCode but I have manually to type it in every time I want to remove this.

So the question is, is it possible to automate this kind of task? I know there are some external tools ( https://code.visualstudio.com/docs/editor/tasks ) but I'm struggling to get it working...

Edit: Example requested (my regex is working, that's not the problem:/. I need an example how to automate this task... )

EXAMPLE

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

Expected Output

Test User

This extension does the job:

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

It seems like the regex adheres to:

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

Example

Create a file regex.json :

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

"info" is just a reminder, doesn't do anything.

Set a shortcut in keybindings.json :

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

You can batch multiple commands together [{...},{...}] which is useful for applying a whole set of regex operations in one go.

As of today, it seems it's still not possible without an extension. Here are 2 other extensions than the one proposed in the accepted answer (both are also open-source):

Batch Replacer (but it doesn't work on the documents open in the editor : "you must have a folder open for editing and all files in it will be updated." * )

Replace Rules : you simply add some rules in your settings.json (open the palette with F1 or ctrl+shift+p and select Preferences: open settings (JSON) ).

"replacerules.rules": {
    "Remove trailing and leading whitespace": {
        "find": "^\\s*(.*)\\s*$",
        "replace": "$1"
    },
    "Remove blank lines": {
        "find": "^\\n",
        "replace": "",
        "languages": [
            "typescript"
        ]
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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