in reply to Multiline match for empty string

Rather than positively matching against empty lines, why don't you match negatively for non-whitespace characters?

#!/usr/bin/perl use strict; use warnings; my $tests = '% only 1 profile is allowed '; my $regex = '\S'; if($tests !~ qr{$regex}ms) { print "$tests\n REGEX MATCHED\n"; } else { print "$tests\n FAILED!\n"; }

You could also dynamically build your regular expression based upon the string itself:

my $regex = '^\n{' . $tests =~ tr/\n/\n/ . '}';

If neither of these meet spec, I'd appreciate a more thorough description of what you mean by "maintain this multiline match regex format". I sense this is an XY Problem.

Replies are listed 'Best First'.
Re^2: Multiline match for empty string
by josh803316 (Beadle) on Aug 05, 2010 at 17:19 UTC
    What I mean is, in the flow of the application I can only pass a regex but the logic of the comparison won't change:
    $tests =~ qr{$regex}ms

    So I was wondering if there was a regex I could pass besides ^$ that would fail the match for anything that wasn't a single empty space ''.
      It's probably easier and cleaner to just write a one-off test rather than working within this fixed framework, but you could use this to check if your test string contains only whitespace:

      my $regex = q|(??{'\s{' . length($tests) . '}'})|;

      This requires you to include use re 'eval'; at some point in scope. It also requires that the name of of the variable being tested is literally $tests - if not, you need to modify the string accordingly.

      How it works:
      The expression uses Perl code executed at matching time - see (??{ code }) in perlre. The string literal stored in $regex is (??{'\s{' . length($tests) . '}'}). When the regular expression is executed, Perl concatenates '\s{', the length of the variable $tests and '}'. The resulting regular expression requires that the string in question match exactly as many whitespace characters as there are characters in the string, i.e. contain only whitespace. You should also note that this opens up some security holes in Perl, as discussed in (??{ code }) and in A bit of magic: executing Perl code in a regular expression from perlretut.

        Thanks for the help!! The system is a complete automation application which allows users to enter expected results and to allow the step to pass/fail based on the comparison of the expected result vs the actual result. I've allowed the inclusion of regular expressions in the expected result but I can't change the matching logic on the fly so I need something that will match multi-line and single line as well as empty text. I added some logic from the original suggestion so that If the expected result is an empty string I do the negative match and for all other strings I proceed with the normal multiline match. Thank you again for the help!!!