in reply to Re: regex question
in thread regex question

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 ?

Replies are listed 'Best First'.
Re^3: regex question
by pjotrik (Friar) on Sep 01, 2008 at 07:29 UTC
    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.
Re^3: regex question
by moritz (Cardinal) on Sep 01, 2008 at 07:40 UTC
    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.

Re^3: regex question
by JadeNB (Chaplain) on Sep 01, 2008 at 18:05 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 ?
    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.