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

Hello guys (and Gals),

I need a regular expression that will search for every other 2 characters in a string.

I.E.

__data__ 1 2 3 4 5 6 7 8 9 1 0 Need to capture 1 2 5 6 9 1
Thanks

Replies are listed 'Best First'.
Re: Reg Ex Needed
by Abigail-II (Bishop) on Jan 19, 2003 at 16:50 UTC
    That's not "every other 2 characters", unless you think that spaces aren't characters. You could do something like:
    $result = join "" => /(..).?.?/gs; # Assume string in $_

    Abigail

      Thanks!
Re: Red Nex Needed
by Chady (Priest) on Jan 19, 2003 at 16:46 UTC

    should it be a regex?

    you can use a hash to hold the data and check if an element has occured more than once.
    my %temp; my @captured = grep { defined $temp{$_}++ } split / /, <DATA>;
    If you need exactly two, try this
    my %temp; my @captured = grep { ++$temp{$_} == 2 } split / /, <DATA>;

    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/
Re: Reg Ex Needed
by BrowserUk (Patriarch) on Jan 19, 2003 at 19:33 UTC

    A non-regex version. It grabs every second pair of space delimited strings in the line.

    my $data = '1 2 3 4 5 6 7 8 9 1 0' print join ' ', grep $_,(split' ', $data)[ map{ my $n = 4 * $_; ( $n, +$n + 1 ) } 0..5 ]; 1 2 5 6 9 1

    Adjust 0 .. 5 to suit the maximum number of items/4


    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.

Re: Reg Ex Needed
by hotshot (Prior) on Jan 19, 2003 at 16:47 UTC
    I don't know of regexp for that (maybe others can be more helpful), but if you split the string to an array (assuming the charecters always separated by spaces), you can grep on the array according to the indexes of the array (take entries if arrIndex%4 == 0 or 1)

    Hotshot
Re: Reg Ex Needed
by Gilimanjaro (Hermit) on Jan 20, 2003 at 14:21 UTC
    $data =~ s/(....)(....)/$1/g;

    is your regex... Funny way to store the data though... First of all, as someone else said, you're not looking for characters, you're looking for character/space pairs.

    In fact you're looking for pairs of character/space pairs.

    In fact you're looking for every other pair of character/space pairs...

    The nice way:

    @characters = <DATA> =~ /(.) /g; while(@characters) { push @pairs, [shift @characters, shift @character +s] } @selection = map { $pairs[$_*2] } (0..@characters/2);