PERL / CHAPTER 07

Anchored parsing and captures

Advanced

Validate a complete text shape before using captured fields.

By the end of this chapter

  • Anchor a whole-string match
  • Capture only the required fields
  • Use captures only after a successful match

The idea

Enter with strings and conditional statements understood. Regular expressions describe text patterns. Parentheses capture selected portions of a successful match, while repetition operators describe how many characters may occur. A search pattern can match a substring inside a larger string, so whole-input validation needs explicit boundaries. This chapter uses ASCII character classes where an input format requires ASCII letters or digits.

Use \A and \z to anchor the beginning and absolute end of a string. This avoids accepting an unexpected trailing newline when strict validation is intended. Read captures inside the successful branch rather than assuming they describe a failed attempt. A regex can verify a textual shape, but business constraints such as an allowed numeric range still need a separate check. Keep those two responsibilities visible.

Perl example
use strict; use warnings;
my $text="box:12";
if ($text =~ /\A([a-z]+):([0-9]+)\z/) {
 print "$1 $2\n";
} else { print "invalid\n"; }
Result
box 12

The entire string has lowercase ASCII letters, a colon, and digits. The two capture groups provide the name and count.

Try it yourself

Validate exactly two uppercase ASCII letters followed by three ASCII digits, with no extra characters.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which pair anchors the absolute beginning and end of a Perl string?