Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to represent "NOT" in a group

Tags:

java

regex

I have this Regex:

<(\d+)>(\w+\s\d+\s\d+(?::\d+){2})\s([\w\/\.\-]*)(.*)

What I want to do is to return FALSE(Not matched) if the third group is "MSWinEventLog" and returning "matched" for the rest.

<166>Apr 28 10:46:34 AMC the remaining phrase
<11>Apr 28 10:46:34 MSWinEventLog the remaining phrase
<170>Apr 28 10:46:34 Avantail the remaining phrase
<171>Apr 28 10:46:34 Avantail the remaining phrase
<172>Apr 28 10:46:34 AMC the remaining phrase
<173>Apr 28 10:46:34 AMC the remaining phrase
<174>Apr 28 10:46:34 Avantail the remaining phrase
<175>Apr 28 10:46:34 AMC the remaining phrase
<176>Apr 28 10:46:34 AMC the remaining phrase
<177>Apr 28 10:46:34 Avantail the remaining phrase
<178>Apr 28 10:46:34 AMC the remaining phrase
<179>Apr 28 10:46:34 Avantail the remaining phrase
<180>Apr 28 10:46:34 Avantail the remaining phrase

How to put " NOT 'MSWinEventLog' " in the regex group ([\w\/\.\-]*) ?

Note :
The second phrase above should return "not matched"

like image 993
Joe Ijam Avatar asked Apr 28 '10 03:04

Joe Ijam


2 Answers

<(\d+)>(\w+\s\d+\s\d+(?::\d+){2})\s(?!MSWinEventLog)([\w\/\.\-]*)(.*)

a negative lookahead (here: '(?!MSWinEventLog)') should be enough:

Negative lookahead is indispensable if you want to match something not followed by something else.
When explaining character classes, I already explained why you cannot use a negated character class to match a "q" not followed by a "u". Negative lookahead provides the solution: q(?!u).

like image 82
VonC Avatar answered Sep 21 '22 16:09

VonC


You can do it with negative lookahead:

<(\d+)>(\w+\s\d+\s\d+(?::\d+){2})\s(?!MSWinEventLog)([\w\/.-])(.)
                                   -----------------

(?!MSWinEventLog) will match only if not immediately followed by an expression matching "MSWinEventLog".

like image 22
Etaoin Avatar answered Sep 19 '22 16:09

Etaoin