tags:

views:

61

answers:

3

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.

+4  A: 

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'
KennyTM
+1: 3 seconds faster
Mark Byers
Similarly to @Mark, I got `bash: !LoginException$: event not found`. And didn't work in Textpad. Do they use a different RegEx syntax?
Marcus
Not sure `^` and `$` are correct here - @Marcus wanted to "find" these strings (so I suppose he means "within a larger body of text"), not match a regex against them. Perhaps he should clarify his question...
Tim Pietzcker
@Marcus, @Tim: See update.
KennyTM
Hmm.. I get: grep: illegal option -- P / Usage: grep -hblcnsviw pattern file . . .
Marcus
+2  A: 

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
Mark Byers
I added a `\b` or this regex would happily match "oginException" after having skipped the "L".
Tim Pietzcker
Tried this in bash, got `bash: !Login: event not found`. Also didn't work in Textpad..
Marcus
@TimPietzcker: Good spot.
Mark Byers
@Marcus: Can you post the command you are using?
Mark Byers
`grep (?!Login)\b\w+Exception mylog.log`. And then using the Textpad GUI.
Marcus
+2  A: 

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
Greg Bacon
Fair enough but there are n number of exceptions I want to know about and only 1 I don't want to know about. And I can't list all the possible positives.
Marcus
@Marcus So why doesn't throwing away the ones you don't care about using `grep -v LoginException` as in the latter example do the trick?
Greg Bacon
Yup, using the 'two-stage pipeline' approach.. Thanks.
Marcus