包含一个字符串且不包含另一个字符串的行的正则表达式 [英] Regex for lines containing one string and not containing another string

查看:144
本文介绍了包含一个字符串且不包含另一个字符串的行的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have following regex handy to match all the lines containing console.log() or alert() function in any javascript file opened in the editor supporting PCRE.

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

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

But I encounter many files containing window.alert() lines for alerting important messages, I don't want to remove/replace them.

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

So the question how to regex-match (single line regex without need to run frequently) all the lines containing console.log() and alert() but not containing word window. Also how to escape round brackets(parenthesis) which are unescapable by \, to make them part of string literal ?

我试过跟随正则表达式但是徒劳无功:

I tried following regex but in vain:

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


推荐答案

你应该使用负面看起来像这样:

You should use a negative lookhead, like this:

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

负面看如果字符串窗口。存在,则断言不可能匹配。

The negative lookhead will assert that it is impossible to match if the string window. is present.

正则表达式演示

对于括号,您可以使用反斜杠,但因为你有一个单词边界字符,如果你放入转义括号,它将不匹配,因为它们不是单词字符。

As for the parenthesis, you can escape them with backslashes, but because you have a word boundary character, it will not match if you put the escaped parenthesis, because they are not word characters.


元字符\ b是一个类似于插入符号和美元符号的锚点。
它匹配一个称为字边界的位置。此匹配
为零长度。

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:


  • 在字符串中的第一个字符之前,如果第一个字符是
    字符。

  • 在字符串中的最后一个字符之后,如果最后一个
    字符是单词字符。

  • 在字符串中的两个字符之间,
    其中一个是单词字符而另一个不是单词字符。

这篇关于包含一个字符串且不包含另一个字符串的行的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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