Other than "don't do it with REs", I have a couple of thoughts...

You can "fix" your RE using the highly experimental extended pattern "(?>pattern)". This prevents your patterns matching the non-warning tags spanning into other tags. The modified pattern is:

<para0[^>]*>\s*(?><applic[^>]*>.*?</applic\s*>)?\s*(?><title[^>]*>.*?< +/title\s*>)?\s*(?><capgrp[^>]*>.*?</capgrp\s*>)?\s*(<warning[^>]*>\s* +.*?\s*</warning\s*>)

I don't understand your criteria: you say you want to match "the first warning element directly parented by a para0 element". I see two such elements in your sample data:

<warning> <?warningcaution MOD_A ### ID_1?> <para>moda id1 warning</para> </warning>

and

<warning> <?warningcaution MOD_C ### ID_3?> <para>modc id3 warning</para> </warning>

So, I don't understand why you say "If warning MOD_A/ID_1 is removed, my expected response is no match." instead of matching the second warning directly parented by para0. I am misunderstanding something or you have a contradiction in your requirements.

Another RE you might consider is the following:

<para0[^>]*?>(?>\s*<([^ >]*?).*?>.*?</\1(\s[^>]*)?>)*?\s*(<warning>.*? +</warning>)

This assumes that none of the tags directly under the para0 tag nest within themselves but it does not need to be modified if the set of possible tags changes. Note that this pattern has two capture buffers, so your warning will be in $2 if there is a match.


In reply to Re: regex - need first child of parent by ig
in thread regex - need first child of parent by kdolan

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.