I would like to match the following: Match A, optionally followed by any number of characters not containing Z, followed by Z, with the additional restriction that *if* there are characters between A and Z, the character immediately following A must be a space. In case of a match, grab what is between A and Z.

Examples for matching strings:

Example for non-matching strings: The obvious solution, as far I can see, goes like this:
if(/^A (?: Z |(\s.*?) ) Z$/x) { $grabbed=$1//'' }
I don't like the repeating of Z in this pattern. Any suggestion for a more elegant way to do this?

Update: I just came up with this:
if(/^A ( \s (?:.*?) )? Z$/x) { $grabbed=$1//'' }
This seems to fulfil the condition. Still, if you have nice alternatives, I would like to see them. Plus, is there a way to write the regexp so that $1 is always defined in case of a match? Right now it is undef if the string to match is AZ (that's why I have to use the // operator).
-- 
Ronald Fischer <ynnor@mm.st>

In reply to This regexp made simpler by rovf

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.