在 VSCode 正则表达式搜索中匹配文件的开头 [英] Match the beginning of a file in a VSCode regex search

查看:230
本文介绍了在 VSCode 正则表达式搜索中匹配文件的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 VSCode 正则表达式搜索中匹配文件的开头以查找并删除以下模式:

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.

我想删除所有包含 //\n 作为第一个字符的文件中的第一行.但是,当我对 //\n 执行正则表达式搜索时,它显然会匹配所有文件中的所有出现,无论它们在文件中的位置如何.

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.

正则表达式语言提到存在 \A 以匹配行的开头或某些编辑器中的文件,但 VSCode 拒绝此正则表达式为无效:\A//\n.

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.

所以我的问题是,如何在 VSCode 中匹配文件的开头来实现我的需要?

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

推荐答案

Visual Studio Code 正则表达式中文件的开头可以匹配

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

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

你可以使用

查找内容:^//\n([\s\S\r]*)
替换为:$1

或者,由于现在 VSCode 支持 Lookbehinds 作为现代 JS ECMAScript 2018+ 兼容环境,您也可以使用

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

查找内容:^(?<![\s\S\r])//\n
替换为:空

如果您想知道为什么使用 [\s\S\r] 而不是 [\s\S],请参考 Visual Studio Code 中的多行正则表达式.

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

详情

  • ^ - 一行的开始
  • // - // 子串
  • \n - 换行符
  • ([\s\S\r]*) - 第 1 组 ($1):任何 0 个或更多字符,直到文件末尾.
  • ^ - 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.

^(? 正则表达式表示:

  • ^(?<![\s\S\r]) - 仅匹配第一行的开头,因为 ^ 匹配行的开头并且 (?<![\s\S\r]) 如果当前位置的左侧有任何 1 个字符,则负向后视匹配失败
  • //\n - // 和换行符.
  • ^(?<![\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.

这篇关于在 VSCode 正则表达式搜索中匹配文件的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆