Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl regex - How to make it less greedy?

Tags:

regex

perl

How do I count the number of empty 'fields' in the following string ? Empty fields are indicated by -| or |-| or |- The regex I have cooked up seems to be working except when I have consecutive empty fields ? How do I make it less greedy ?

my $string = 'P|CHNA|string-string|-|-|25.75|-|2562000|-0.06';
my $count = () = ($string=~/(?:^-\||\|-$|\|-\|)/g);   
printf("$count\n");

The above code prints 2 instead of 3 which I want.

like image 416
Jean Avatar asked Oct 16 '13 21:10

Jean


1 Answers

I'd avoid the regex route entirely for this and instead treat this like a list, because it is one:

my $count = grep { /^-$/ } split /\|/, $string;
like image 87
AKHolland Avatar answered Nov 03 '22 02:11

AKHolland