Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reject a string if preceded by another string using standard POSIX regex?

I have a regex which finds errors in a log for me:

/(exception|error)/i

This works, except that I do not want to be alerted when the following occurs, which I expect to happen:

DD/MM/YYYY 10:20pm: Read exception encountered

How do I specifically reject the 'Read exception encountered' string? I'm trying to use the ?! operator, but failing:

/(?!Read exception encountered)(exception|error)/i

The above still matches the string I want to exclude.

UPDATE: After experimenting with the negative lookbehind and lookahead solutions below, I have discovered that SiteScope supports only basic POSIX regex features, not extended features. Is a solution possible using only basic POSIX regex features?

like image 332
David Smith Avatar asked Jul 11 '13 18:07

David Smith


3 Answers

You want to use "Negative Lookbehind" (if it's supported by your regex engine.) effectively you say "I want to match X patern, as long as this other pattern does NOT preceed it."

In your example, it looks like this:

/(?<!read )(exception|error)/i

see more about "lookaround" features here.

like image 164
Robert P Avatar answered Nov 05 '22 17:11

Robert P


If you're looking to reject the entire string if the sub-string Read exception encountered is in the string, then I would simply use a negative look ahead which is supported by most languages.

^(?![^\r\n]*?\bRead exception encountered\b)[^\r\n]*?(exception|error)

Live example: http://www.rubular.com/r/CV7P9huVsI

enter image description here

like image 1
Ro Yo Mi Avatar answered Nov 05 '22 18:11

Ro Yo Mi


Try something like this /([^R][^e][^a][^d]) (exception|error)/

like image 1
rjhdby Avatar answered Nov 05 '22 18:11

rjhdby