Search code examples
regexvisual-studio-coderegex-lookaroundsregex-group

Match all spaces after a particular string


Doing a find and replace in VsCode on a large amount of files. I'm looking to replace all spaces after a set of quotes, but only on a specific line.

I can very easily find all spaces using \s+, but I don't understand how to capture only the spaces after a specific string(one specific line). I've tried positive look behinds, but I can only get it to match the first space, but I need to match all spaces on that line.

Example code:

variable = "01 - Testing this thing"

I need to find and replace all the spaces between the quotation marks with underscores, but I can't get any regex to match all the spaces between the quotes. I might want to replace the dash(-) as well, but the spaces are more important and I'm struggling to figure it out.


Solution

  • Here is a pretty good workflow.

    1. Open a Search Editor (from the Command Palette or set a keybinding to it).
    2. Use this regex (?<=variable = ")[^"]*.
      That will find all matches in all files in your workspace or whatever folders you designate in the file to include filter. I suggest setting the context lines option to 0.
    3. Ctrl+Shift+L to select all your matches. The matches are the 01 - Testing this thing part.
    4. Now do a regular find in that search editor tab - with the Find in Selection option enabled.
    5. Simply doing a find of and replaceAll with _ will make all those changes (in the Search Editor only).
    6. To apply those changes to all the files with your initial search results, use the extension search-editor-apply-changes Apply Search Editor Changes... command.

    Then you can check to see if the changes were as you expected and save all. It will open all affected files so you can inspect them.


    Seems like a few steps but notice the first regex can be very simple. And then you are doing a simple find/replace in just those selections. Demo:

    Apply changes from search editor demo