Entry
I want to look for a text, then grab the next 2 characters after the found text. Please Help!
Apr 25th, 2003 21:18
Colin Thomsen, Chris Leon,
Regular expressions would work well for this job. You need to put the
unknown text into a string (we'll call it $string) and the text to find
in another string (call it $textToFind).
Then you apply a regular expression to the string using the format:
$string =~ //;
In your example you want to first match the text to find, which you can
do:
$string =~ /$textToFind/;
Then you want to return the next two characters, which you do using ().
Anything inside the () is returned in the special variable $1. The next
set of () is returned in $2 and so on. To match any character, you can
use the special '.' matching character:
$string =~ /$textToFind(..)/;
print $1;
Note that the above code assumes that the string does have the text you
are looking for. If you're not sure, use an if, as follows:
if ($string =~ /$textToFind(..)/) {
print $1;
} else {
print "$textToFind not found!";
}
The complete program is listed below:
#!/usr/bin/perl -wT
my $string = "somestring text12";
my $textToFind = "text";
if ($string =~ /$textToFind(..)/) {
print "$1\n";
}