in reply to regex question

It also works if you make the second capture "greedy":
print "$1 $2\n" if($str=~/(.*?)\*(.*)/); # Remove "?" in second capt +ure
The reason is that "Non greedy" dot-star matches NOTHING, so it prints nothing.

     Have you been high today? I see the nuns are gay! My brother yelled to me...I love you inside Ed - Benny Lava, by Buffalax

Replies are listed 'Best First'.
Re^2: regex question
by Alien (Monk) on Sep 01, 2008 at 07:16 UTC
    But what if I have a string containing "abc*def*ghi" (or any number of "words")? Is there a way to obtain abc,def,ghi without resorting to split ?
      In that case, you can use m//g in list context:
      my $s = 'abc*def*ghi'; my @words = ($s =~ /([^*]+)/g);
        my @words = ($s =~ /([^*]+)/g);
        Note that this code skips empty fields (leading, trailing, or internal)—for example, @words becomes ('a', 'b') if $s is a**b. Of course, this may be the desired behaviour.
      You can't have a dynamical number of captures in Perl 5, which is why you either need split or a regex with the /g modifier in a while loop.

      There are hacks, though:

      $_ = "abc*def*ghi"; my @matches; m/(?: ([^*]+) (?{ push @matches, $^N}) \*?)+/x; print join('|', @matches), $/;

      But before you use this, read the big fat warning in perlre about how experimental (?{ ... }) is.

      But what if I have a string containing "abc*def*ghi" (or any number of "words")? Is there a way to obtain abc,def,ghi without resorting to split ?
      Is it possible that you're not describing what you want to do? Normally, it's good if you can use split—it's much faster for this kind of job than pulling the string apart with regexes. According to Benchmark (with all the usual caveats: on my machine, at this time of day, &c.), split /\*/, $string is about 3 times faster than the clever my @matches = $string =~ /([^*]+)/g suggested in Re^3: regex question.