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

i have a big string, suppose it is a million chars lenght, and i want to extract the letters z v x g from it sequently and assign it to a variable, i can do it in a loop without regex using a loop and if... then ... but i wish a regex procedure for that ,i can't manage to make the following regex to act over the whole string, the following code return only the first occurence which is z here , can you please help me. .
use strict; use warnings; my $a = "bbzvbvxmgbnmnvxyyz"; $a =~ m/([zvxg])/g; print $1;
i wish the program to return zvvxgvxz
thanks

Replies are listed 'Best First'.
Re: extract sequences of certain letters and assign it to a variable
by CountZero (Bishop) on Nov 16, 2008 at 11:44 UTC
    You were almost there:
    use strict; use warnings; my $a = "bbzvbvxmgbnmnvxyyz"; my @all = $a =~ m/([zvxg])/g; print @all;
    Result:
    zvvxgvxz
    Or (but it destroys the original contents of the variable):
    use strict; use warnings; my $a = "bbzvbvxmgbnmnvxyyz"; $a =~ s/[^zvxg]//g; print $a;

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: extract sequences of certain letters and assign it to a variable
by LanX (Saint) on Nov 16, 2008 at 13:06 UTC
    I understood that you want to extract sequences not single characters contained in your characterclass ... (?)

    so maybe you need one more + in CountZeros code to get substrings instead of letters.

    please compare the differences:

    use strict; use warnings; my $a = "bbzvbvxmgbnmnvxyyz"; my @all = $a =~ m/([zvxg])/g; print "@all\n"; @all = $a =~ m/([zvxg]+)/g; print "@all\n"; __END__ # OUTPUT FOLLOWS z v v x g v x z zv vx g vx z

    Cheers LanX

    - - - - - Which song???

Re: extract sequences of certain letters and assign it to a variable
by bart (Canon) on Nov 16, 2008 at 13:59 UTC
    Homework?

    Anyway, the shortest command in Perl that'll do what you ask for, is:

    tr/zvxg//cd
    which does an inplace replacement, deleting all characters that are not one of those four.