Search code examples
regexvisual-studio-codefindinfiles

VSCode: Regex to 'Replace in Files' multiple matches after a specific word


I have a bunch of files which have a specific line in which I need to do some find & replace (via VSCode function 'Replace in Files' (Ctrl+Shift+H)).

Imagine the following (as-is):

---
Created at: 2017-03-09
Last updated at: 2017-03-09
tags: #On-going #Future_Fixes
---

I would need the following (to-be):

---
Created at: 2017-03-09
Last updated at: 2017-03-09
tags:
  - On-going
  - Future_Fixes
---

Basically I need, in a list of files, to have in every line that starts with tags: string, to replace all # by \\n - .

Find: (?<=tags:)\s#+
Replace by: \n -

What I get is:

---
Created at: 2017-03-09
Last updated at: 2017-03-09
tags:
  - On-going #Future_Fixes
---

So it seems to be running only on the first instance, but not for the following terms I want to match.

Can anyone share any insights that may help achieve the above?

Thanks in advance.


Solution

  • It is very tricky to do this with a lookbehind in vscode's search across files because, as you know, it doesn't support non-fixed length lookbehinds. Some answers will just suggest that you run a find/replace multiple times changing one match at a time until you have changed them all. If you wanted to do that try this:

    find: (?<=tags:)(.*)\s#
    replace: $1\n -

    and keep running the search and replace all until it doesn't find anything anymore. If you have 2 items in the tags you would have to run this twice.

    But, vscode does support non-fixed length lookaheads. So if your tags: line is always followed by the --- line then you can do this:

    #(?=.*\n---)
    

    and replace as you had: \n - .

    It is just looking for #'s with a --- on the next line. You only have to run this once no matter how many tags items there are.

    See Regex101 demo.