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

标签 javascript regex editor pcre

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

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

但是我遇到许多包含用于提醒重要消息的 window.alert() 行的文件,我不想删除/替换它们。

所以问题是如何正则表达式匹配(单行正则表达式,无需频繁运行)包含 console.log()alert() 但不包含的所有行包含单词window。另外如何转义 \ 无法转义的圆括号(括号),使它们成为字符串文字的一部分?

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

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

最佳答案

您应该使用否定的lookhead,如下所示:

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

负向查找头将断言如果字符串 window. 存在,则不可能匹配。

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.

关于javascript - 包含一个字符串且不包含另一字符串的行的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37394458/

相关文章:

javascript - 如何在 JavaScript 中向 SVG 对象添加过滤器?

java - MySQL 中的 REGEXP 返回不需要的值

ios - 检查有效的 vimeo url ios

python - 如何提取与文本文件中的正则表达式匹配的行号

windows - "edit"不是 cmd.exe 中的有效命令?

javascript - 使用 execCommand 切换 H1 和 h2

editor - 触摸打字员如何在 vi 中导航?

php - 获取在 PHP 中重定向的远程图像

javascript - 如何从电子邮件 ID 数组中提取名称数组

javascript - 使用 Mocha 测试 Promises 时,如何在发生错误时打印完整的堆栈跟踪