Matching multiple values in a string

I've been battling with parsing a comma-delimited string, and have had what I would call B- success. I'm using perl and trying to parse out specific identifiers from a string, into a new string. When things are "normal," my regex works fine. When things get complicated, my script fails miserably. I think a loop is in order, but often find that someone here has a more elegant way to do things.

Specifically, my script has 2 variables that I'm concerned with: $identifier and $key. $key is just an integer - it could be 7, 77, etc. $identifier is a string that contains a number of codes. I'm trying to pull out the codes that match $identifier and concatenate them in a new string.

For example, (this is one of the difficult ones),

$key = 7
$identifier = "CODES: L7,BT7-1,CP87,E7"

The desired result would be: $parsed = "L7,BT7-1,E7" since they are all of the "7" codes. 87 is a separate identifier. If it's just 7s, I'm OK. When there are other numbers containing 7, or they appear at the beginning or end, I have problems.

Any help or suggestions would be greatly appreciated. Just need something to break the mental log jam that is preventing me from seeing the obvious!

Thanks, Doug

May we see the regex you are using?

---------- Post updated at 11:31 AM ---------- Previous update was at 11:24 AM ----------

If you don't mind breaking up the tasks, something like this may work for you:

sub parse {
  my $key        = shift;
  my $identifier = shift;

  my ($list) = $identifier =~ m{^CODES: (.*)};
  my @list = ();

  foreach my $e (split /,/, $list) {
      push @list, $e if $e =~ m{\D$key(?:-\d+)?};
  }

  return @list if wantarray;
  return join ',', @list;
}


my $parsed = parse(7, "CODES: L7,BT7-1,CP87,E7");

$\ = "\n";
print $parsed;