Confusing
Previous  Top  Next

Everything we did so far was not even remotely confusing, but I'll try to come up with some weird examples that make you at least sweat a little bit. I have to admit that I'm no master at regular expressions, but let's just see. In this case we simply want to extract the age out of the string.

1: $text = "Ingmar is 25 years old";
2:
3: ($age) = $text =~ /is\s(\d\d)\syears/;
4:
5: print "Age: $age";

Here we make sure that is and years surround the age. The $age has to be in brackets, as does (\d\d). However, this only works with a two digit age. What about our younger friends? We just get two digit numbers here, but we want any kind of number. We change line 3 to

3: ($age) = $text =~ /is\s(\d+)\syears/;

and we catch any age. The + means that it's previous pattern should be matched either one time or any times!