regexreplacevisual-studio-codevscode-tasks

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

Solution

  • This extension does the job: ssmacro

    It seems like the regex adheres to JavaScript 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.