Home > Mobile >  Regex: negative lookbehind not directly before target
Regex: negative lookbehind not directly before target

Time:05-15

I am debugging some JavaScript code and I need to identify lines that contain " = " followed by a comparison operator such as "==", ">", "<", "!=". However, I want to ignore lines that are preceded by the start of a for loop. So I want to identify lines like this:

x = (y > z) * 2;

but ignore lines like this:

for (var i = 1; i<5; i ) {

This would require a negative lookbehind, I believe. But the text "for ", which I would put in the negative lookbehind, does not immediately precede the text I want to match.

I tried this regular expression in Notepad :

(?<!for .*) = .*(==|>|<|!=)

but it was reported as "invalid" because a quantifier inside a lookbehind makes it a non fixed width.

On the other hand, this regex works but doesn't help me because "for " does not immediately precede the text I want to match:

(?<!for ) = .*(==|>|<|!=)

Any suggestions would be appreciated.

CodePudding user response:

Try a negative lookahead:

^(?!.*for ).* = .*(==|>|<|!=)

If you don't want to match the "for" part, throw in another capture group, and access / replace on that group

^(?!.*for ).* (= .*(?:==|>|<|!=))

A bit more robust (tolerant of absent whitespace, and <= >=, but digusting):

^(?!.*?\bfor\b).*?[^\n!<>=](=[^\n=].*?(?:[<>]|[!=<>]=))

EDIT:

I had to insert ^, to assure the match started at the beginning of the line. Depending on your regex flavor, ^ may match the beginning of a line or beginning of the text in its entirely. If its the latter, you'd have to use something like (?<=^|\n), a positive lookbehind, instead of ^ (which works in your case for Notepad ).

  • Related