How to read the next word after a keyword found
How to read the next word after a keyword found
(OP)
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
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
RE: How to read the next word after a keyword found
$_="The blue cat ( run over the car).";
/cat\s/;
@after=split(/\s/,$');
print $after[0],"\n";
#$after[0] is what you want
RE: How to read the next word after a keyword found
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.
http://www.oac-design.com
RE: How to read the next word after a keyword found
@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.
RE: How to read the next word after a keyword found
Sincerely,
Tom Anderson
CEO, Order amid Chaos, Inc.
http://www.oac-design.com
RE: How to read the next word after a keyword found
$string =~ /cat\b\s*(\S+)/;
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