正则表达式为多个值的负查找

时间:2021-08-12 13:22:48

I want to search my logs for exceptions. Starting Regex:

我想在日志中搜索异常。从正则表达式:

\wException\b

(The \w is so that I'm catching names of exceptions e.g. InvalidOperationException, and not just the word "exception", and the \b is to exclude other forms of exception e.g. "SomeExceptionHandler".)

(\w是为了捕获异常的名称,例如InvalidOperationException,而不仅仅是“exception”一词,而b是排除其他形式的异常,例如:“SomeExceptionHandler”。)

This worked well, but I found one exception recurring very frequently that I'm not interested in; let's call it FooException. I changed my regex to include a negative lookbehind:

这个方法很有效,但我发现一个异常经常出现,我对此不感兴趣;我们叫它FooException。我将regex更改为包含一个负面的外观:

\w(?<!Foo)Exception\b

Great, now "FooException" has been excluded. Now I find that BarException is also creating a lot of noise and I want to exclude that too. So I figured I'd try a pipe inside the lookbehind:

很好,现在“FooException”已经被排除在外。现在我发现BarException会产生很多噪音我也想排除它。所以我想我应该在后视镜里尝试一下:

\w(?<!(Foo|Bar))Exception\b

...but that was rejected as an invalid regex.

…但那被拒绝作为无效的regex。

So, how can I exclude multiple strings in the lookbehind?

那么,如何在lookbehind中排除多个字符串呢?

1 个解决方案

#1


2  

You didn't mention which tool you are using, but it is most likely rejecting your pattern because variable length lookbehinds are not supported by most regex flavors.
A simple workaround is to have multiple look-behinds:

您没有提到正在使用的工具,但它很可能会拒绝您的模式,因为大多数regex风格都不支持可变长度的外观。一个简单的解决办法是有多个后视镜:

\w(?<!Foo)(?<!Bar)Exception\b

You can also match the full exception:

您还可以匹配完整的异常:

\b(?!Foo|Bar)\w+Exception\b

#1


2  

You didn't mention which tool you are using, but it is most likely rejecting your pattern because variable length lookbehinds are not supported by most regex flavors.
A simple workaround is to have multiple look-behinds:

您没有提到正在使用的工具,但它很可能会拒绝您的模式,因为大多数regex风格都不支持可变长度的外观。一个简单的解决办法是有多个后视镜:

\w(?<!Foo)(?<!Bar)Exception\b

You can also match the full exception:

您还可以匹配完整的异常:

\b(?!Foo|Bar)\w+Exception\b