如果子串匹配,则正则表达式排除特定行

时间:2016-06-10 16:04:31

标签: regex

我一直试图运行一个正则表达式但是无法正确运行。假设我的文件包含以下行:

java.SocketException
java.Exception
Exception
RuntimeException
1 RuntimeException`

我想编写一个将排除" SocketException"的正则表达式。但是应该允许其他人。一个简单的egrep -v" SocketException"工作良好。但我的正则表达式位于一个配置文件中,另一个内部程序将使用它来解析文件。

我尝试过多种方式:

egrep '?(!Socket)Exception' my.log
egrep '?!(Socket)Exception' my.log
egrep '(?<!(Socket))Exception' my.log

但我不能只排除SocketException。

感谢任何帮助。

关心-Amit

1 个答案:

答案 0 :(得分:0)

描述

^(?!.*SocketException).*$

Regular expression visualization

此表达式将查找不包含SocketException

的行

实施例

现场演示

https://regex101.com/r/zV1qX7/1

示例文字

java.SocketException
java.Exception
Exception
RuntimeException
1 RuntimeException`

样本匹配

java.Exception
Exception
RuntimeException
1 RuntimeException`

解释

NODE                     EXPLANATION
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
----------------------------------------------------------------------
    .*                       any character (0 or more times (matching
                             the most amount possible))
----------------------------------------------------------------------
    SocketException          'SocketException'
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  .*                       any character (0 or more times (matching
                           the most amount possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------