Hi Monks

I'm continuing my exploration of Perl and currently exploring regular expressions.

For this simple test, I have a small string of KEY=value pairs, separated by ';' characters. I am trying to identify if a particular KEY has a certain value and a different KEY does not contain a value.

I have code which follows which does this with two regexs:

#!/usr/bin/env perl use strict; use warnings; use 5.016; for (<DATA>) { chomp; print "Match: $_\n" if /name=bob/ and not /flags=.*?cat.*?;/; } __DATA__ name=bob;flags=human;age=10 name=tiddles;flags=cat,black;age=3 name=bob;flags=cat,white;age=6

In this simple example, I'm looking to get the line which matches a name of 'bob' and flags does not contain 'cat'. This code works and returns the single matching line.

However, I tried combining the regexes and using lookaheads to match multiple conditions, but this is currently failing. My code for this follows

#!/usr/bin/env perl use strict; use warnings; use 5.016; for (<DATA>) { chomp; print "Match: $_\n" if /(?=name=bob)(?!flags=.*?cat.*?;)/; } __DATA__ name=bob;flags=human;age=10 name=tiddles;flags=cat,black;age=3 name=bob;flags=cat,white;age=6

My understanding is that this matches if name is set to 'bob' and flags do not contain 'cat' (searching up to the first semicolon). However, it returns both 'bob' lines.

Am I missing something obvious here? I understand that lookaheads are zero-width matches, but maybe this is something to do with anchoring?

PS: I know this could probably be done simpler by splitting on ';' into a hash and validating the hash, but this is a learning exercise :)

Many thanks


In reply to Multiple regexs into single combined regex using lookaheads by mxb

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.