Other posters were correct when they changed things from using the {min,max} quantifier notation on the inside of the capture buffer to using the '?' quantifier on the outside. There is a crucial difference between "empty but matching" and "not matching", and {0,1} doesnt have the same behaviour as '?' even though they are functionally equivelent. (This may be construed as a bug :-) Alternatively you can do what i do below, which is to put the capture inside of an alternation.

Anyway, the following uses the conditional pattern with lookahead/lookbehind to match as you requested. You can play around with it to easily forbid {{hello}}, as the current code allows it.

use strict; use warnings; for ( 'oh {hello} there', 'oh {hello there', 'oh hello there', 'oh hello} there', 'of {{hello}} there', ) { if ( $_ =~ / (?: ( \{ ) # capture a '{' | # or (?<! \{ ) # not preceded by a '{' ) hello # .. followed by 'hello' (?(1) # if (defined $1) \} # match an '}' | # else (?! \} ) # not followed by a '}' ) # /x) { print "YEP : $_ : ", defined $1 ? "'$1'" : 'undef', " - $&\n"; } else { print "NOPE: $_\n"; } } __END__ YEP : oh {hello} there : '{' - {hello} NOPE: oh {hello there YEP : oh hello there : undef - hello NOPE: oh hello} there YEP : of {{hello}} there : '{' - {hello}

Also I changed your diagnostic code, you were using $1 even when the match failed, which meant you were getting the wrong thing.

---
$world=~s/war/peace/g


In reply to Re^3: Regex conditional match if previous match in same expression is true? by demerphq
in thread 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.