14

I'm trying to match the beginning of a file in a VSCode regex search to find and remove the following pattern:

//
Anything else to leave in place
etc.

I'd like to remove the first line in all files that contain //\n as the first characters. However when I perform a regex search for //\n it matches all occurences in all files obviously, regardless of their position in the file.

The regex language mentions the existence of \A to match the beginning of a line, or file in some editors, but VSCode rejects this regex as invalid: \A//\n.

So my question is, how can I match the beginning of a file in VSCode to achieve what I need?

Florian Bienefelt
  • 1,448
  • 5
  • 15
  • 28
  • How about a negative lookbehind on `.`? That should only match stuff not preceded by anything at all. seems lookbehind [doesn't actually work on VSCode](https://stackoverflow.com/q/42179046/395685). – Nyerguds Feb 06 '20 at 08:52

2 Answers2

34

The beginning of a file in Visual Studio Code regex can be matched with

^(?<!\n)
^(?<![\w\W])
^(?<![\s\S\r])

You may use

Find What: ^//\n([\s\S\r]*)
Replace With: $1

Or, since nowadays VSCode supports lookbehinds as modern JS ECMAScript 2018+ compatible environments, you may also use

Find What: ^(?<![\s\S\r])//\n
Replace With: empty

If you wonder why [\s\S\r] is used and not [\s\S], please refer to Multi-line regular expressions in Visual Studio Code.

Details

  • ^ - start of a line
  • // - a // substring
  • \n - a line break
  • ([\s\S\r]*) - Group 1 ($1): any 0 or more chars as many as possible up to the file end.

The ^(?<![\s\S\r])//\n regex means:

  • ^(?<![\s\S\r]) - match the start of the first line only as ^ matches start of a line and (?<![\s\S\r]) negative lookbehind fails the match if there is any 1 char immediately to the left of the current location
  • //\n - // and a line break.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • 2
    `^(?<![.\n])` is probably incorrect: it will look for places that are not preceded by newlines (good) and actual dots (not good). I use just `^(?<!\n)` – Desmond Hume Oct 18 '21 at 18:38
  • @DesmondHume You know, it is working, but you are right that `\n` alone in the lookbehind will do. – Wiktor Stribiżew Oct 18 '21 at 20:25
0

Already has a great answer, just one more example.

I have ansible files that start with

---

And i wanted to insert above the file mode

# code: language=ansible

VSCode search & replace

^(?<![\s\S\r])---\n

# code: language=ansible\n---\n

Pieter
  • 1,916
  • 17
  • 17