Madean
Madean

Reputation: 129

Regular Expression to match two strings in AND condition

I am new to regular expression, please kindly help me on the error scenario where I need to use regex to match two error messages (appearing in different lines, but same paragraph) in AND condition from a log file:

Msg1 - ERROR [com.company.util.ejb.TimedBean] () FAILED processing Loader

Msg2 - java.lang.RuntimeException: Message code:[SL] is unknown.

Basically, what I need is to match (msg1)&&(msg2), in this case, (ERROR...Loader) will appear in the first line and (java...unknown) will follow in the next line. The messages will always follow this order. I am not programming in any typical language here, they will be put into a enterprise tool that accepts regexp.

If possible, would you also show me how to make it in Or condition as (msg1)||(msg2)?

Upvotes: 0

Views: 1291

Answers (1)

csd
csd

Reputation: 1784

Matching two consecutive lines is, in theory, just a matter of putting the two regular expressions end-to-end. So for purposes of illustration, let's say you've got a file named logfile.txt that contains messages you're looking for. Then from a Linux command line you could do something like this:

pcregrep -M -o '^ERROR\N*Loader$\njava\N*unknown\.$\n' logfile.txt

and it would print the line pairs that you're looking for. Breaking it down into parts:

  • ^ERROR matches the word ERROR at the beginning of a line.
  • \N* matches any number of characters that aren't a line terminator.
  • Loader$ matches the word Loader at the end of a line.
  • \n matches the newline character. (Might be different on Windows.)
  • java\N*unknown\.$\n is more of the same.

BUT... And this is a big problem... The tool that handles your regular expression must be capable of doing multi-line matches, and that capability must be turned on. (That's what the -M command line option to pcregrep enables.) Many regexp tools, such as plain grep on many systems, can't do multiline searches. So you may be out of luck.

Upvotes: 1

Related Questions