Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Misunderstanding negative look behind

by bronto (Priest)
on May 31, 2012 at 11:31 UTC ( #973500=note: print w/replies, xml ) Need Help??

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

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!


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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://973500]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (10)
As of 2017-01-20 12:14 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (174 votes). Check out past polls.