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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

search text and return a given string

Status
Not open for further replies.

NateBro

Programmer
Sep 1, 2004
233
US
ok, i tried looking for this and have not found anything :(

basicly i have a web site seach script, and i want this script to find a word and return the whole sentence that word is in like so.

Code:
my $search_word = 'another';
my $text = "this is a sentance. this is another sentance.";

 if ($text =~ m/$search_word /i){
 $search_return = 'this is another sentance.';
 }


ok, how do i pull $search_return out of $text?

i'm so lost, thanks so much for your time! :)
 
Well, perl doesn't know a sentence from a "sentance", you have to tell perl where the sentences begin and end. A common way is to split a string on the sentence ending punctuation marks:

Code:
my $search_word = 'another';
my $text = "this is a sentance. this is another sentance.";
my @text = split(/[.?!]/,$text);
foreach my $sentence (@text) {
   print $sentence if ($sentence =~ m/$search_word/i);
}

There must be many modules dealing with something like this that will return more accurate results then the above crude code.
 
Code:
use strict;
use warnings;

my $search_word = 'another';
my $text = "this is a sentance. this is another sentance. And another"; # [i]sic.[/i]

my @sentences = split(/[.!?]/, $text);

my @hits = grep {/$search_word/i} @sentences;

print join("\n", @hits);
will give you a rough approximation. But parsing sentences is hard to get right - the above example will parse the following lines incorrectly as two sentences
Code:
"Ah, Dr. Watson, I see you are recently returned from Afghanistan."
"How do I parse sentences?" asked Nate.
But if you only need a crude solution, it'll do.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top