in reply to Re: Regex to capture every readable character except COMMA
in thread Regex to capture every readable character except COMMA

my $regex = qr/ \A [^,]+ \Z /x;
...
my $flag  = 1 if $var =~ /\G ($regex) /gcx;

Because  qr/ \A [^,]+ \Z /x matches an entire string, the  /g regex modifier has no meaning (and it's also used in a boolean context). Likewise the  /c modifier. Likewise the  \G anchor. Likewise the capture group around the  $regex regex object, although in the original code a capture may be pertinent.

>perl -wMstrict -le "my $rx = qr/ \A [^,]* \z /x; ;; for my $s (',abcd', 'abc,d', 'abcd,', ',,,', 'abcd', '.;$%&', '') { print qq{'$s' }, $s =~ $rx ? '' : 'NO', ' match'; } " ',abcd' NO match 'abc,d' NO match 'abcd,' NO match ',,,' NO match 'abcd' match '.;$%&' match '' match

Replies are listed 'Best First'.
Re^3: Regex to capture every readable character except COMMA
by Athanasius (Archbishop) on Jan 09, 2014 at 08:36 UTC

    Good points! So maybe a regex like this, using a positive lookahead, would be more useful here:

    use strict; use warnings; my $regex = qr/ ([^,]+) (?=\Z|,) /x; my $var = 'abcd,ef,,ghijkl,mnop'; print "$1\n" while $var =~ /$regex/g;

    Output:

    18:27 >perl 827_SoPW.pl abcd ef ghijkl mnop 18:27 >

    But then, the same result can be obtained by discarding the regex and using split instead:

    use strict; use warnings; my $var = 'abcd,ef,,ghijkl,mnop'; my @matches = split /,/, $var; $_ && print "$_\n" for @matches;

    ;-)

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      My interpretation of the OP is that the OPer is trying to capture entire strings that contain no commas. If one is trying to extract sub-string sequences that contain no commas, split seems like a good way to go. BTW: For the latter purpose, a regex without explicit capture or look-ahead can also be used:

      >perl -wMstrict -le "my $regex = qr/ [^,]+ /x; my $var = 'abcd,ef,,ghijkl,mnop'; printf qq{'$_' } for $var =~ /$regex/g; " 'abcd' 'ef' 'ghijkl' 'mnop'

      (Although as Anonymonk has pointed out below, the latter interpretation puts you dangerously close to territory dominated by Text::CSV and its ilk.)