Perl: regular expressions: yesterday’s code explained
The tutor tells the workings of yesterday’s pattern matching example.
In yesterday’s post I mention that the regular expression
if ($input=~/item1[^0-9]*[0-9]*.?[0-9]{0,2}/i)
can find the pattern item1….$#####.## in a longer string. Here are some explanatory points:
- =~ is the pattern find operator, which finds the pattern defined on the right in the string on the left.
- Between / / is the pattern to be matched.
- item1, between / /, means the literal string item1.
- [^0-9]* means not numbers, while the asterisk means 0 or more.
- [0-9]* means numbers only, 0 or more of them.
- .? means possibly a single decimal point, but maybe none.
- [0-9]{0,2} means numbers, 0 to 2 of them.
- The i after the closing slash means case insensitivity: item1 or Item1 will be found.
- The match, if found, is put in the variable $&, which can afterwards be printed or fetched as desired.
HTH:)
Source:
McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.