Forum Moderators: coopster & phranque

Message Too Old, No Replies

Matching multiple occurances of a string within an array

         

skube

2:29 am on Dec 4, 2003 (gmt 0)

10+ Year Member



Ok, say I have a long array and want to match all occurances of two particular strings

@myarray = (the dog, the cat, the dog and cat);
$string1 = "dog";
$string2 = "cat";

How do I match all occurances of my two strings?

DrDoc

3:20 am on Dec 4, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What do you want to do with the "match" once you've ensured that it IS a match?
Or, is there something you want to do to all elements in the array that do NOT match?

skube

10:34 pm on Dec 5, 2003 (gmt 0)

10+ Year Member



Well I would be assigning matches to a variable, and then doing various maniuplations.

example:
$myvar =~ /[cat¦dog]/g

DrDoc

11:10 pm on Dec 5, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



As in, for each match, append the matching part of the string (or, the whole string?) to the variable? Or, do something in a foreach loop? Or, make each match an element in an array?

panoylis

1:34 pm on Dec 9, 2003 (gmt 0)

10+ Year Member



I don't really get your question but some thoughts that may help you:

#Lets say this is an array:

my @foo=("Dog", "Cat", "Dog and Cat", "Dog, Cat and Dog");

#parse this from a loop
for (my $i=0;$i<=@foo;$i++) {
print "in \$foo[$i] found a Dog\n" if ($foo[$i]=~/Dog/);
print "in \$foo[$i] found a Cat\n" if ($foo[$i]=~/Cat/);
print "in \$foo[$i] found more Dogs\n" if ($foo[$i]=~/Dog.*Dog/);
}

This will print :

in $foo[0] found a Dog
in $foo[1] found a Cat
in $foo[2] found a Dog
in $foo[2] found a Cat
in $foo[3] found a Dog
in $foo[3] found a Cat
in $foo[3] found more Dogs

___________
Panos

alexhudson

7:00 pm on Dec 9, 2003 (gmt 0)

10+ Year Member



More thoughts - I can't believe I'll have missed anything here :o)

my @a = qw/cat dog cat_and_dog/;
my $search = qr/Cat/i; # I'm searching for 'cat'

# find all elements with 'cat' in them:
my @b = grep {/$search/} @a;

# find indices of elements with 'cat' in them:
my ($i, @c) = (0);
map { push @c, $i if /$search/; $i++ } @a;

# find all parts in array that match search term (this
# is why I made the regex case-insensitive....!)
my @d;
map { push @d, $1 if /($search)/; } @a;

print<<_END_;
Results
=======
Variable\tContents
\@b\t\t@b
\@c\t\t@c
\@d\t\t@d
_END_

Results I get (remember, stringified arrays have their elements separate by spaces):

Results 
=======
Variable Contents
@b cat cat_and_dog
@c 0 2
@d cat cat

Has to be one of these, right?!