简体   繁体   中英

Regex and grep exception matching

I tested my regex for matching exceptions in a log file :

http://gskinner.com/RegExr/

Regex is :

.+Exception[^\n]+(\s+at.++)+

And it works for couple of cases I pasted here, but not when I'm using it with grep :

grep '.+Exception[^\n]+(\s+at.++)+' server.log

Does grep needs some extra flags to make it work wit regex ?

Update:

It doesn't have to be regex, I'm looking for anything that will print exceptions.

Not all versions of grep understand the same syntax.

  • Your pattern contains a + for 1 or more repeats, which means it is in egrep territory.
  • But it also has \\s for white space, which most versions of grep are ignorant of.
  • Finally, you have ++ to mean a possessive match of the preceding atom, which only fairly sophisticated regex engines understand. You might try a non-possessive match.

However, you don't need a leading .+ , so you can jump right to the string you want. Also, I don't see why you would use [^\\n] since that's what . normally means, and because you're operating in line mode already anyways.

If you have grep -P , you might try that. I'm using a simpler but equivalent version of your pattern; you aren't using an option to grep that gives only the exact match, so I assume you want the whole record:

$ grep -P 'Exception.+\sat' server.log

But if that doesn't work, you can always bring out the big guns:

$ perl -ne 'print if /Exception.+\sat/' server.log

And if you want just the exact match, you could use

$ perl -nle 'print $& if /Exception.*\bat\b.*/' server.log

That should give you enough variations to play with.

I don't understand why people use web-based “regex” builders when they can just do the same on the command line with existing tools, since that way they can be absolutely certain the patterns they devise will work with those tools.

You need to pass it the -e <regex> option and if you want to use the extended regex -E -e <regex> . Take a look at the man: man grep

It looks like you're trying to find lines that look something like:

... Exception foobar at line 7 ...

So first, to use regular expressions, you have to use -e with grep , or you can just run egrep .

Next, you don't really have to specify the .+ at the start of the expression. It's usually best to minimize what you're searching for. If it's imperative that there is at least one character before "Exception", then just use . .

Also, \\s is a perl-ish way of asking for a space. grep uses POSIX regex, so the equivalent is [[:space:]] .

So, I would use:

 grep -e 'Exception.*[[:space:]]at'

This would get what you want with the least amount of muss and fuss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM