包含一个字符串但不包含另一个字符串的行的正则表达式

Regex for lines containing one string and not containing another string

我有以下正则表达式可以方便地匹配在支持 PCRE 的编辑器中打开的任何 javascript 文件中包含 console.log()alert() 函数的所有行。

^.*\b(console\.log|alert)\b.*$

但是我遇到很多文件包含 window.alert() 行来提醒重要消息,我不想 remove/replace 它们。

所以问题是如何正则表达式匹配(单行正则表达式不需要经常 运行)所有包含 console.log()alert() 但不包含单词 [=17= 的行].还有如何转义 \ 无法转义的圆括号(圆括号),使它们成为字符串文字的一部分?

我试过遵循正则表达式但没有成功:

^.*\b(console\.log|alert)((?!window).)*\b.*$

你应该使用一个负面的 lookhead,像这样:

^(?!.*window\.).*\b(console\.log|alert)\b.*$

如果字符串 window. 存在,否定的 lookhead 将断言不可能匹配。

Regex Demo

小括号可以用反斜杠转义,但是因为你有分词字符,如果你把转义的括号放在一起就匹配不上了,因为他们不是单词字符。

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a "word boundary". This match is zero-length.

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.