I apologize for the confusing title, I'm in new regex territory (for me) here. I've been working my way through the excellent Mastering Regular Expressions, but I must be missing something.

I'm attempting to solve a problem wherein I'm finding a particular string in text: this string is optionally surrounded by '{' and '}'. In other words, the closing brace needs to be matched if and only if the opening brace was there.

I simplified the issue to a very minimal case in order to construct the regex, but I am getting unexpected results. Perhaps a more savvy monk than I can enlighten me as to where I've gone wrong.

use strict; use warnings; for ( 'oh {hello} there', 'oh {hello there', 'oh hello there', 'oh hello} there', ) { print '', ( $_ =~ / ([{]{0,1}) # optional opening brace hello # .. followed by 'hello' (?(1)\}) # a closing brace iif the open brace was the +re /x ? 'YEP ' : 'NOPE' ), " - $1\n"; }

This program outputs the following lines:

YEP  - {
NOPE - 
NOPE - 
YEP  - 

Expected / desired results are:

YEP  - {
NOPE -
YEP  -
NOPE -

What in the world am I missing?

<radiant.matrix>
Ramblings and references
The Code that can be seen is not the true Code
I haven't found a problem yet that can't be solved by a well-placed trebuchet

In reply to Regex conditional match if previous match in same expression is true? by radiantmatrix

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.