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

How to read the next word after a keyword found

Status
Not open for further replies.

Sina

Technical User
Jan 2, 2001
309
0
0
CA
Hello everyone,

HOw can I read the next word after a keyword if found in a string.

i.e
The blue cat ( run over the car).

I like to say, if the word "cat" found, read the next character or word which is in this case "(" or it could be a period or a ";" or even another word.

and ignoring any spaces
Thanks much
 
#! usr/bin/perl
$_="The blue cat ( run over the car).";
/cat\s/;
@after=split(/\s/,$');
print $after[0],"\n";


#$after[0] is what you want

 
Code:
my $string = "The blue cat ( run over the car).";
my $word = "cat";
$string =~ /$word\s*?(\S+)/;
my $next_word = $1;
print qq~The word after "$word" is "$next_word".~;
This will only find the first instance in the string. If the string were "The big cat ate the little cat for dinner.", then it would stop after "cat ate".
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
an addition to marblcat's reply

@after=split(/\s+/,$');

The addition of the + in the pattern let's it match one or more white-space characters, the other \s should be \s+ as well.
Mike

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

It's like this; even samurai have teddy bears, and even teddy bears get drunk.
 
Oh yeah, that reminds me... by using \s*?, it will in fact return "fish" after "cat" if you had "catfish". But by using + instead of *, then you only match the whole word instead of a part of the word.
Sincerely,

Tom Anderson
CEO, Order amid Chaos, Inc.
 
A slight modification of Tom's regex:
[tt]
$string =~ /cat\b[/red]\s*(\S+)/;
[/tt]
This will capture the '(' from your posted string and any word that follows cat, like 'in' from "cat in the hat". It will also capture a '.' or a ';' that follow cat (typically without a space), but won't capture 'alogue' from "catalogue" or 'fish' from "catfish". The '\b' matches a word boundary, which is the nonspace between a word character, \w, and a non-word character, \W.

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top