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

The following doesn't use the (?() pat) construct but it does use a similar setup - and it prints out the correct output:

for ( 'oh {hello} there', 'oh {hello there', 'oh hello there', 'oh hello} there', ) { our $paren; if (/ ({ | (?<!{)) # optional opening brace (?{ $paren = $^N }) # store for later hello # .. followed by 'hello' (??{$paren ? "\}" : "(?!\})"}) # a closing brace if the open +brace was there /x) { print "Yep - $1\n"; } else { print "Nope\n"; } }


I tried briefly to get the (?() ) form to work but couldn't get it to go.

my @a=qw(random brilliant braindead); print $a[rand(@a)];
  • Comment on Re: Regex conditional match if previous match in same expression is true?
  • Download Code

Replies are listed 'Best First'.
Re^2: Regex conditional match if previous match in same expression is true?
by ikegami (Patriarch) on Apr 09, 2007 at 19:48 UTC

    That doesn't give me the desired results at all. I was using Perl 5.6, but $^N was only introduced in 5.8.

    By the way, you should localize your package variables whenever possible. Replace
    our $paren;
    with
    local our $paren;

    I'd also add a comment along the lines of "Always use package variables with regular expressions." Someone reading or maintaining the code could very well not know that lexical variables can cause problems.

    Finally, to avoid continually compiling regexp fragments, replace
    (??{$paren ? "\}" : "(?!\})"})
    with
    (?(?{ $paren }) } | (?!}) )

      Note that Rhandom and I basically posted the same pattern, the main difference being mine doesn't need the (?{})/(??{})/$^N stuff, using the conditional pattern instead (as you originally requested).

      Actually to be honest I didnt really look deeply at Rhandom's post before I posted mine. Its cool we came up with the same thing pretty much, but using two different advanced feature sets.

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

        Aye, I noticed that after I replied. I didn't mean to diminish your post. I basically stopped following the thread after Rhandom posted.