http://qs321.pair.com?node_id=973500


in reply to Misunderstanding negative look behind

First of all, thanks to all those who commented. Unfortunately, nobody really captured what my problem is, and the answers don't match the question. Usually, when this happens it's the asker's fault, so please excuse me if I didn't state my question clearly.

My question is: I need one regular expression, which matches lines in an hosts file where the name of a certain machine appears (qualified or not), and it's not associated to that machine's address or to 127.0.1.1.

BrowserUk's solution doesn't work, because it doesn't cover the case where there is something else between the hostname and the address.

cosimo's example is catching a good record, not a bad one, so it's out too.

moritz's procedure doesn't use a single regex, so that doesn't apply as well.

I was trying to solve that with negative lookbehind (match this name that it's not preceded somewhere in the line by...) but that didn't work for some reason. And, as it turned out, it was even overly complicated.

The right solution was found by oha, uses negative lookahead (instead of lookbehind), and it's much simpler: this one:

^(?!(127\.0\.1\.1|10\.20\.11\.99)\s)([a-fA-F0-9:\.]+)(\s+[a-zA-Z0-9\.\ +-]+)*(\s+kvm-test-v06(?:\.example\.com))(\s+[a-zA-Z0-9\.\-]+)*\s*

(Some extra grouping is my fault, not oha's).

I didn't realize that I could say "the beginning of the line is not followed by..." and use lookahead instead of lookbehind.

Thanks all for trying! And double thanks to oha!

Ciao!
--bronto


In theory, there is no difference between theory and practice. In practice, there is.