XML technologies / Regular expressions / Perl / Perl’s regex dialect / regex operands and regex literals

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

The bottom entries in the table Perl regex elements: overview are headed “Only in regex literals.” A regex literal is the “Regex” part of m/Regex/, often loosely called the regular expression. Before reaching the regex engine, text between slashes is parsed using specific rules similar to quoted strings. However, Perl knows this is a regex and differs slightly in some respects. These rules provide special ways to build regexes.

For example, variables in regex literals are interpolated. If $num contains 20, the literal m/:.{$num}:/ becomes ˹:.{20}:˼. This builds regexes from pieces. Another feature converts letter case. For example, \U...\E uppercases the regex, so m/abc\Uxyz\E/ becomes ˹abcXYZ˼. This trivial example could simply be written ˹abcXYZ˼. It becomes useful with interpolated variables. If $tag contains “title”, then m{</\U$tag\E>} produces ˹</TITLE>˼.

Instead of a literal, the regex operand can be a string or any Perl expression, for example:

$MatchFeld = "^Subject:"; # Normale String-Zuweisung
   .
   . 
   .
if ($text =~ $MatchFeld) {
   .
   . 
   .

If $MatchFeld is used as the operand of =~, its contents are interpreted as an actual regex, not a literal. Thus, variables are not interpolated and \Q...\E is unsupported.

More interestingly, replace

$text =~ $MatchFeld

with

$text =~ m/$MatchFeld/

. The result is identical: this literal consists solely of the interpolated value of $MatchFeld. Interpolated contents are not processed as a second regex literal, so \U...\E and $var receive no special handling within it. See How regex literals are parsed for precise parsing details.

When a regex is reused, string versus literal input has important efficiency consequences, discussed under Regex compilation, /o, qr/.../, and efficiency.

 

Regex literal features

Regex literals support:

 

Variable interpolation

Variables starting with $ or @ are replaced by their values, or interpolated. With $, the scalar value is inserted. With @, array or slice elements are inserted separated by spaces, more precisely by $", a space by default. In Perl, ›%‹ denotes hashes, but their interpolation is not intuitively defined, so hashes are not interpolated.

 

Names for Unicode characters

Specifying “use charnames ':full';” lets you name Unicode characters using \N{Name}. For example, \N{LATIN SMALL LETTER SHARP S} denotes “ß”. All names Perl recognizes appear in UnicodeData.txt in the installation's unicore directory. Print the full path with:

use Config;
print "$Config{privlib}/unicore/UnicodeData.txt\n";

Forgetting “use charnames ':full';” or the colon before “full” is easy, and breaks \N{...} sequences. \N{...} also does not work with overloaded regex literals, discussed below.

 

Lowercase or uppercase the next character

The sequences \l and \u lowercase or uppercase the next character (\l for lowercase, lowercase; \u for uppercase, uppercase). Usually they precede a variable. For example, if $title contains “mr.”, then m/...\u$title.../ produces the regex ˹...Mr....˼. The Perl functions lcfirst() and ucfirst() do the same.

 

Lowercase or uppercase a range

The sequences \L and \U convert everything through the end of the literal or the next \E to lowercase or uppercase. For example, the earlier $title with the literal m/...\U$title\E.../ becomes ˹...MR....˼. They correspond to Perl functions lc() and uc().

Combine single-character and range sequences: m/...\L\u$title\E.../ produces ˹...Mr...˼, regardless of the original case.

 

Treat a range as literal text 

After \Q , regex metacharacters are escaped with backslashes (Q for “quoted”) through the string's end or \E. Only regex metacharacters are escaped, not regex-literal features such as interpolation, \U, or of course \E itself. Strangely, unknown escapes such as \F or \H are not escaped, but warn “Unrecognized escape \F passed through”.

In practice this rarely matters, since \Q...\E usually handles interpolated text, correctly neutralizing all metacharacters. For example, if $title contains “Mr.”, then m/...\Q$title\E... produces ˹...Mr\....˼. It searches for the string in $title, not the regex in $title.

This is particularly useful for user-entered strings. m/\Q$BenutzerEingabe\E/i performs a case-insensitive literal search for that input. The Perl function quotemeta() is equivalent to \Q...\E in a regex literal.

 

Overloading 

With Regex overloading, literal regex parts can be preprocessed arbitrarily. This interesting feature has implementation limits; see Overloading regex literals for details.

 

Regex operand delimiters

Perl unusually lets you choose literal delimiters freely. Slashes are normal in m/.../, s/.../.../ or qr/.../, but almost any nonalphanumeric character except whitespace works. Common examples:

m!...!      m{...}
m,...,      m<...>
s|...|...|  m[...]
qr#...#     m(...)

  • The four right-hand cases are special: m(...), m{...}, m[...] and m<...> use paired delimiters that may nest if balanced. Since parentheses and brackets often occur within regexes, m(...) and m[...] are less attractive than the others. With the /x modifier, formatting like this is possible:

m{
    Regex  # Kommentare
    hier   # hier
}x;

In substitutions, paired regex delimiters require a second pair for the replacement, of the same or another type. Examples:

s{...}{...}
s{...}!...!
s<...>(...)
s[...]/.../

Whitespace may separate the pairs. Replacement details appear under The replacement operand.

  • Question-mark delimiters give special, rarely used match-once behavior (see Special match-once searches with ?...?).

  • Literals are parsed like strings with regex-aware differences. Single-quote delimiters disable this string processing. With m'...', variables are not interpolated, and string-processing sequences such as \Q...\E and the \N{...} construct do not work. m'...', for example, may help with regexes containing many @.

The match operator's initial m may be omitted with slash or question-mark delimiters. Thus these two lines

$text =~ m/.../;
$text =~  /.../;

are identical. I always specify m explicitly.

  

 

 

 

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

back to top