Further to GrandFather's wise advice on regex factoring, here's another approach.

The idea is that the requirement to "not match ... if ... a certain server name or a certain string comes before Servername" suggests a negative look-behind assertion. The problem with this is the inference I make that the look-behind could be variable-width, and such a look-behind is not directly supported in Perl 5. (I am perhaps improperly reading into the above quotation the possibility that there could be two or more strings of differing lengths to be excluded.)

A variable-width negative look-behind can be emulated. The trick is that a positive match on one of several completely arbitrary patterns causes a substring needed in a subsequent match to be 'consumed', and then the whole sub-match is 'failed', preventing the subsequent match from succeeding. See  (*SKIP) and  (*FAIL) (only available in 5.10+) in the Special Backtracking Control Verbs section of perlre.

>perl -wMstrict -le "my @strs = ( 'Servername FOO', 'fine Servername FOO yyy', 'no Servername FOO zzz', 'cool Servername BAR', 'nyet Servername BAR vvv', 'Servername BOFF', 'ok Servername BOFF yyy', 'no Servername BOFF zzz', ); ;; my @names = qw(FOO BAR); my @avoid = qw(no nyet); ;; my $find = join '|', @names; $find = qr{ Servername \s+ (?: $find) }xms; ;; my $not_before = join '|', @avoid; $not_before = qr{ (?: $not_before) \s+ Servername }xms; $not_before = qr{ (?: $not_before (*SKIP)(*FAIL))? }xms; ;; for my $s (@strs) { print qq{'$s'} if $s =~ m{ $not_before $find }xms; } " 'Servername FOO' 'fine Servername FOO yyy' 'cool Servername BAR'

In reply to Re: perl regexp question excluding strings by AnomalousMonk
in thread perl regexp question excluding strings by bobg2011

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.