in reply to Re^2: Regex conditional match if previous match in same expression is true?
in thread Regex conditional match if previous match in same expression is true?

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.

  • Comment on Re^3: Regex conditional match if previous match in same expression is true?
  • Download Code