pepijn has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm not doing perl normally but I need to atm. Just a simple question. I'm not looking for people to solve my entire problem, just a little help to get started.

I have a string "abcd bcde cdef defg" and I only need all occurences of "cde" to be returned into an array. Giving me in this case an array with 2 values being both "cde".

How can I become this by using a regex ? (I'm actually not looking for "cde" but another variable thing, but that regex is way to long for just this question).

Any help is welcome, also just a URL to a certain site etc...

Thanks in advance,

pepijn

  • Comment on Matching multiple occurences in one string

Replies are listed 'Best First'.
Re: Matching multiple occurences in one string
by borisz (Canon) on Feb 27, 2004 at 17:16 UTC
    #!/usr/bin/perl $_ = "abcd bcde cdef defg"; # @x is a array with as much 'cde' scalars as in $_ @x = /cde/g; print "@x\n"; # count how often cde is in $_ $anz = () = /cde/g; print "$anz\n"
    Boris
      thanks, works just fine, now tuning the regex :)
Re: Matching multiple occurences in one string
by Limbic~Region (Chancellor) on Feb 27, 2004 at 17:12 UTC
    pepijn,
    I believe the following will do:
    my @results = $string =~ /(cde)/g; # Also check out perldoc -f quotemeta if cde is actually a $var
    Cheers - L~R

    Update: I almost forgot my manners. Welcome to the Monastery. The site and community is quite large and may seem a bit overwhelming. If so, be sure to check out the PerlMonks FAQ.