Off Topic RegEx Question
David Landgren
david at landgren.net
Wed Aug 27 16:45:39 PDT 2003
Roger Williams wrote:
> I know thins is not the place but I know one of you know this one off the
> top of your head.
>
> I have:
>
> $list = "dog 1 1 1 cat 2 1 snake 111"
> and I want to end up with:
> dog 1 cat 2 snake 1
> I thought
> $list =~ s/ \d \d/ \d/g;
> would do the trick, but that gives me:
> dog d 1 1 cat d snake d 1
\d in the RHS of the s/// doesn't do much (as you can see...)
Try:
$list =~ s/(\d)\d*(?: \d+)*/$1/g;
Capture a digit, maybe followed by more digits, then followed maybe by
groups of space and digits. Replace all that by the captured digit.
Note that this will transform:
dog 1 4 7 cat 2 1 snake 123 => dog 1 cat 2 snake 1
rather than:
dog 1 4 7 cat 2 1 snake 123 => dog 7 cat 2 snake 3
I assume since cat 2 1 => cat 2 that you always want the first digit
matched.
http://www.perlmonks.org/ is a good place to ask Perl questions.
David
More information about the freebsd-questions
mailing list