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

Your expression just never needs to match the braces at all. If you add \s at the beginning and end of the expression (to force Perl to look at something beyond 'hello'), you get the expected result.

Update: In my fooling around, I'd also changed ([{]{0,1}) to ([{])? (because the first version, as merlyn says, will always match, but sometimes an empty string). That's also necessary to make it work as expected.

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

    I'm not interested in matching whitespace -- my examples just happen to have some. I would want the results listed as "desired" in the node even if all whitespace was removed.

    <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 that case, how about this:

      use Test::More; my %tests = ( 'hello' => 1, '{hello}' => 1, 'hello}' => 0, '{hello' => 0, 'oh {hello} there' => 1, 'oh {hello there' => 0, 'oh hello there' => 1, 'oh hello} there' => 0, ); plan 'tests' => scalar keys %tests; while ( my ( $text, $result ) = each %tests ) { my $hello = qr/hello/; my $test_result = ( $text =~ / \{$hello\} # hello with braces | # or (?<! \{ ) # not a brace $hello # hello (?! \} ) # also not a brace /x ) ? 1 : 0; is( $test_result, $result, $text ); }

      Put your (possibly complicated) match text in a variable so you don't have to change it in two places when it changes. After that, literally match the text with braces and without.