Reputation: 33
I need to scan log file to find some substrings.
How to combine conditions below in single regex expression:
I tried something like (?!DDD|EEE|FFF)(AAA|BBB|CCC) but was not successful.
Regular expression syntax should be supported by the Java Pattern class.
Thank you!
Upvotes: 2
Views: 516
Reputation: 12268
I came up with this one:
(?!.*?(DDD|EEE|FFF).*?)(?<!(DDD|EEE|FFF))(AAA|BBB|CCC)
It seems to work, using these test cases:
123AAA //matches
123BBB //matches
123CCC //matches
123DDD //no match
123EEE //no match
123FFF //no match
AAADDD //no match
EEEBBB //no match
Explanation: Don't match if there's "DDD", "EEE", or "FFF" anywhere in the string.
Don't match if there was a "DDD", "EEE", or "FFF" before the matching substring. (I don't know why this is needed. If I leave it out, "EEEBBB" gets a match, and I think it shouldn't. I need to figure this out.)
Update: I think I needed the negative lookbehind because I wasn't considering the context of where the substring match occurred within the line.
Here's a version that doesn't require the negative lookbehind:
(?!^.*?(DDD|EEE|FFF).*?$)(?:^.*?(AAA|BBB|CCC).*?$)
Seems to work because I'm considering the whole line.
Another update. (Can't leave it alone.) This is optimized a bit:
(?!^.*?(?:DDD|EEE|FFF).*$)^.*?(AAA|BBB|CCC).*$
Upvotes: 1