Marcus Leon
Marcus Leon

Reputation: 56699

Regular expression literal

As I'm RegEx dyslexic.. what RegEx can you use to find each of the following strings - with the exception of "LoginException"?

NullPointerException
LoginException
BooException
Abc123Exception

Edit: To be clear, I'm looking for these strings in a text/log file.

Upvotes: 2

Views: 668

Answers (3)

Greg Bacon
Greg Bacon

Reputation: 139631

In general, when you want a regular expression that matches anything except a particular string or pattern, it's almost always more straightforward to invert the sense of the test. So instead of “here’s a pattern I hope matches anything except XYZ,” check whether XYZ matches and throw away the positives.

If you want only those three, use

$ egrep '(NullPointer|Boo|Abc123)Exception' input.log

You could probably get away with a two-stage pipeline, e.g.,

$ grep Exception input.log | grep -v LoginException

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 838806

You can use a negative lookahead:

(?!Login)\b\w+Exception

You can do it for example with Perl:

perl -ne 'print if /(?!Login)\b\w+Exception/' < mylog.log

Upvotes: 2

kennytm
kennytm

Reputation: 523574

Assuming PCRE (Perl-Compatible RegEx)-like syntax (i.e. grep -P):

\b(?!LoginException\b)\w*Exception\b

Example:

echo "NullPointerException LoginException BooException Abc123Exception LoginFooException" |
grep -P '\b(?!LoginException\b)\w*Exception\b'

Upvotes: 4

Related Questions