我有以下正则表达式,可以方便地匹配在支持 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.
存在,则不可能匹配。
对于括号,你可以用反斜杠转义它们,但是因为你有单词边界字符,所以如果你放转义的括号,它不会匹配,因为它们不是单词字符。
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/