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.

In reply to Re: Misunderstanding negative look behind by bronto
in thread Misunderstanding negative look behind by bronto

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.