Date: Fri, 13 Jul 2001 21:16:11 -0000 From: cberry@cinenet.net (Craig Berry) Subject: Re: regexp question Message-Id: Matt D (emdee@DEMUNGEcwcom.net) wrote: : there's probably a 'doh! of course!' answer to this, but it's eluding : me at the moment... : : i want to capture a keyword and up to 3 words either side of it from a : block of text (keyword could potentially be at the beginning, end or : anywhere in the middle). : : my block of text is a single space-delimited list of words. If the block isn't big and exact spacing doesn't need to be maintained, I'd do it like this: my $block = 'foo blah barg zneeb foo dribble foo glarb doh foo sneex'; my $kw = 'foo'; my @words = $block =~ /(\w+)/g; for (my $i = 0; $i < @words; $i++) { if ($words[$i] eq $kw) { my $lo = $i - 3; my $hi = $i + 3; $lo = 0 if $lo < 0; $hi = $#words if $hi > $#words; print join(' ', @words[$lo..$hi]), "\n"; } } This grabs every instance of 'foo' and up to three words on either side of it. Note that overlapping ranges will work properly. -- | Craig Berry - http://www.cinenet.net/~cberry/ --*-- "Brute force done fast enough looks slick." | - William Purves