skip to Main Content

I’m using vsc and I want to convert any number found to fixed 4 digits length using zero padding . For example :
2 -> 0002
99 -> 0099

Can I use find and replace ? or any extension ?

Thanks

2

Answers


  1. if you want to change the numbers in a file you can use the extension I wrote Regex Text Generator

    • open find: Ctrl+F
    • enable regex search: .* button
    • search for: d+
    • select all (with focus in find dialog): Alt+Enter
    • execute command: Generate text based on Regular Expression (regex)
    • Use match regex: (.*)
    • Use generator regex: {{N[1]:size(4)}}
    • Accept with Return if you see what you like or Escape
    Login or Signup to reply.
  2. Very easy to do with an extension I authored, Find and Transform.

    Make this keybinding (in your keybindings.json):

    {
      "key": "alt+p",                    // whatever keybinding you want
      "command": "findInCurrentFile",
      "args": {
        "find": "\b(\d{1,4})\b",
        "isRegex": true,
    
        "replace": [            // replace with some javascript computation
          "$${",
    
              // $1 is the first capture group from the find regex
            "return '$1'.padStart(4, '0');",
    
          "}$$",
        ],
    
        "postCommands": "cancelSelection",
      }
    }
    

    The "find": "\b(\d{1,4})\b", assumes your numbers are not within other text, like blah123blah.

    If you want to handle the blah123blah case -> blah0123blah, then use the simple:

    "find": "(\d+)",

    Demo using the simple "find": "(\d+)", version:

    demo: replace numbers with padStarted zeros

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search