Perl: using regex (aka regular expression, pattern matching) to find an item and its price in a string

The tutor demonstrates a Perl regular expression that finds an item name and its price in a string.

Suppose you believe that the price of item1 is given in a string, but aren’t sure how exactly it’s said. It could, for instance, say

Item1: $56.77

or

He likes the price of item1 not above $101.21, but understands it may go up soon….

A search for the portion of the string containing item1…$####.## can be executed as follows:

#!/usr/bin/perl
print “Enter the string, please.”;
$input=<STDIN>;
if($input=~/item1[^0-9]*[0-9]*.?[0-9]{0,2}/i){
print “$&\n”;
}
else{
print “Sorry: no match.\n”;
}

I’ll be explaining the workings of this code next post:)

Source:

www.tutorialspoint.com

robert’s perl tutorial

McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply