XML technologies / Regular expressions / Perl / The qr/.../ operator and regex objects
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The qr/.../ operator was briefly discussed under Extended introductory examples and The art of writing regular expressions (see A regex collection, A helping hand guides the engine). It is a unary operator taking a regex operand and returning a regex object. The object can be used for substitution, matching, as the regex operand of split , or as part of a larger regex.
Regex objects mainly package related parts of a regex into variables, making large expressions easier to build clearly. They also let you control compilation and therefore efficiency, as discussed later.
As noted under Regex operand delimiters, you can choose your own delimiters, such as qr{...} or qr!...!. The five general modifiers /i, /x, /s, /m and /o are supported.
Building and using regex objects
The following fragment varies an example from Extended introductory examples (under A regex collection):
my $HostnameRegex = qr/[-a-z0-9]+(?:\.[-a-z0-9]+)*\.(?:com|edu|info)/i;
my $HttpUrl = qr{
http:// $HostnameRegex \b # Hostname
(?:
/ [-a-z0-9_:\@&?=+,.!/~*'%\$]* # Optionaler Pfad ...
(?<![.,?!]) # ... darf nicht mit [.,?!] enden.
)?
}ix;The first line wraps our simple hostname regex in an object stored in $HostnameRegex. Subsequent lines use it to build a larger object recognizing HTTP URLs, stored in $HttpUrl. Such an object can examine text:
if ($text =~ $HttpUrl) {
print "Text enthält eine URL\n";
}Or extract the HTTP URLs directly:
while ($text =~ m/($HttpUrl)/g) {
print "URL gefunden: $1\n";
}We can now replace our simple definition of $HostnameRegex with the more sophisticated one from Practical regex techniques (see Checking a hostname’s syntax):
my $HostnameRegex = qr{
# Einen oder mehrere Teile, durch Punkte getrennt ...
(?: [a-z0-9]\. | [a-z0-9][-a-z0-9]{0,61}[a-z0-9]\. )*
# Top-level-Domains ...
(?: com|edu|gov|int|mil|net|org|biz|info|...|aero|[a-z][a-z] )
}xi;We can use this object just like the simpler one, without interference: it contains neither ˹^˼ nor ˹$˼ at its ends, nor capturing parentheses. We automatically obtain a better, more specific regex for $HttpUrl.
Match modifiers stick
The qr/.../ operator supports the five general modifiers (see Regex modifiers). A modifier specified when creating an object cannot later be changed, even if the object is used inside an m/.../ operator with very different modifiers. For example, the following does not work as intended:
my $WordRegex = qr/\b \w+ \b/; # Hoppla, der /x-Modifikator fehlt
.
.
.
if ($text =~ m/^($WordRegex)/x) {
print "Wort am Anfang gefunden: $1\n";
}The /x modifier is clearly intended to affect how $WordRegex is used , but this fails because the object’s modifiers, including absent ones, are bound to it by the qr/.../ operator when creating the object. Modifiers must therefore be specified when the object is created.
This gives the following working version:
my $WordRegex = qr/\b \w+ \b/x; # Funktioniert!
.
.
.
if ($text =~ m/^($WordRegex)/) {
print "Wort am Anfang gefunden: $1\n";
}Now compare the original with:
my $WordRegex = '\b \w+ \b'; # Normale String-Zuweisung.
.
.
.
if ($text =~ m/^($WordRegex)/x) {
print "Wort am Anfang gefunden: $1\n";
}Unlike the original, this works even though no modifier is specified when assigning to $WordRegex. Here, $WordRegex is an ordinary variable holding a string later interpolated into a regex literal in the m/.../ statement. Building regexes from strings is more cumbersome than from objects for several reasons, including remembering that $WordRegex may be used only with the /x modifier.
Scoped mode modifiers (see Scoped mode modifiers) within the regex could solve this:
my $WordRegex = '(?x:\b \w+ \b)'; # Normale String-Zuweisung.
.
.
.
if ($text =~ m/^($WordRegex)/) {
print "Wort am Anfang gefunden: $1\n";
}Once the regex literal in m/.../ interpolates the string, the engine receives ˹^((?x:\b●\w+●\b))˼, which behaves as intended.
Creating a regex object does just this, except that all four modifiers /i, /x, /m and /s are always explicitly enabled or disabled. qr/\b●\w+●\b/x creates an object whose string form would be ˹(?x-ism:\b●\w+●\b)˼. Note how the parentheses ˹(?x-ism:...)˼ enable the /x modifier and disable the others, /i, /s and /m. Thus, for an object created with qr/.../, the modifiers stick whether explicitly specified or not.
Inspecting regex objects
The preceding section explained how regex objects are logically wrapped in parentheses with mode modifiers, as in ˹(?x-ism:...)˼. These parentheses can be made visible. When a regex object is used where Perl expects a string, Perl conveniently supplies the object’s string representation. For example:
% perl -e 'print qr/\b \w+ \b/x, "\n"'
(?x-ism:\b \w+ \b)Here is the string representation of the earlier $HttpUrl object:
(?ix-sm:
http:// (?ix-sm:
# Einen oder mehrere Teile, durch Punkte getrennt ...
(?: [a-z0-9]\. | [a-z0-9][-a-z0-9]{0,61}[a-z0-9]\. )*
# Top-level-Domains ...
(?: com|edu|gov|int|mil|net|org|biz|info|...|aero|[a-z][a-z] )
) \b # Hostname
(?:
/ [-a-z0-9_:\@&?=+,.!/~*'%\$]* # Optionaler Pfad ...
(?<![.,?!]) # ... darf nicht mit [.,?!] enden.
)?
)String representations of regex objects are very useful for debugging.
Regex objects for efficiency
Regex objects let you control exactly when Perl compiles a regex into its internal form. The art of writing regular expressions discussed general compilation issues; the more complex Perl-specific details appear under Regex compilation, /o, qr/.../, and efficiency.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln