Search code examples
visual-studio-coderegexp-replace

vscode/visual studio make text alphanumeric and lowercase - either extension or search and replace


e.g I have a string.

{28C9A666-3FC5-4E8F-A31F-D8854DB68666}

Now I want to make the above string into

28c9a6663fc54E8fd31fd8854dB68666

Solution

    • The first part of this answer assumes you are using the Find/Replace in a the current file widget, NOT search/Replace across files. The \l option is not working as expected replacing across files. I actually think there is a bug but see at the end I found a form which does work in the search/replace across multiple files panel.

    You can try this (in the Find widget)

    find: ([A-Z])|-
    replace: \l$1

    or

    find: ([A-Z])|[-{}] if you want to get rid of the {} as well.

    You will have to have the Match Case option enabled on the Find Widget.

    or

    find: (\w)|[-{}]
    replace: \l$1

    And you don't have to have the Match Case option enabled. It just matches every alphanumeric character and replaces it by its lowercased version - which for a digit is the same.

    And you probably want to select the string first, and then enable the Find In Selection option as well. And of course, enable the Use Regular Expression option too.

    The find will capture in group 1 all uppercase letters. It will also match the hyphens and {}'s if you wish but do nothing with them, so those will be effectively removed from the result.

    The replace consists of \l (that's a lowercase L) which tells vscode to lowercase the following capture group - which are your capital letters.


    And for searching across multiple files, try this:

    find: \{*([^-{}]*)[-{}]
    replace: \L$1 // use a capital L here

    vscode doesn't like replacing a non-captured but matched character with \L for some reason.


    Sample keybinding to run this find and replace:

    Put this into your keybindings.json:

    {
      "key": "alt+f",
      "command": "runCommands",
      "args": {
        "commands": [
          {
            "command": "editor.actions.findWithArgs",
            "args": {
              "searchString": "(\\w)|[-{}]",  // note double-escape
              "isRegex": true,
              "replaceString": "\\l$1"   // doubl-escape necessary
            }
          },
          "editor.action.replaceAll",
        ]
      },
    }
    

    The editor.actions.findWithArgs by itself will populate the Find Widget with the queries but not actually run the replace. The editor.action.replaceAll will run all the replacements for the current file. If you want to just populate the Find Widget and trigger the replaceAll yourself use this keybinding:

    {
      "key": "alt+f",
      "command": "editor.actions.findWithArgs",
      "args": {
          
        "isRegex": true,
        "searchString": "(\\w)|[-{}]",
        "replaceString": "\\l$1"
    
      }
    },