Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String Minipulation - Find and Chop! 4

Status
Not open for further replies.

andyros

Programmer
Jul 12, 2005
42
GB
Hi all

Got a problem i thought would be fairly easy to figure out :\!

I've got a large string, say of 2000 characters. And a keyword phrase.

What I'd like to do is find the first instance of this keyword phrase in the string, then chop the string to take 50 characters from behind the first instance and 50 characters from infront.

heres a small example scaled down.

string: hello my name is andy
keyword: name

result: my name is


Ideas:

I've thought of splitting the string into an array, then i can loop through this array until i find the phrase and simply take combine the previous 49 array entries and the next 49 to make a new string.

This is my only idea so far and I'm put off by it as it has memory issues - big strings = even bigger arrays!!

any advice is appreciated
andy
 
You can use the index() function to find the first occurrence of "name" in the string. From that, you can calculate the start and end points of the substring you want to take (start point is the value index returns minus 50 - end point is the value index returns plus the length of the string "name" plus 50) and use the substr() function. That'll avoid having to have a string and an array that both hold the same data.
 
What about:
Code:
#!/usr/bin/perl -w
use strict;
my $string   = "hello my name is andy";
my $keyword  = "name";
my $width    = 3;
my ($result) = $string =~ /(.{0,$width}$keyword.{0,$width})/;
print "Result is [$result]\n";



Trojan.
 
nice..

Mike

I am not inscrutable. [orientalbow]

Want great answers to your Tek-Tips questions? Have a look at faq219-2884

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top